java封装了函数,函数要求传入字符串(String)和字节数组(byte[])参数,java类打包封装成dll,以后,在c#.net里引用这个dll,并且调用里面的函数,这时要往里面传入参数,此时直接传c#中的字符串(string)可以,但是字符数组sbyte[]不能直接传入,请问这个问题怎么解决?

解决方案 »

  1.   

    传IntPtr
    IntPtr buff = Marshal.AllocHGlobal(数组大小/以字节为单位);
      

  2.   

    引用这个dll后在C#看到的这个函数的原型是什么?第2个参数的类型变为IntPtr?byte[] bytes=new byte[64];
    IntPtr buff=Marshal.UnsafeAddrOfPinnedArrayElement(bytes,0); //取数组索引为0的元素的地址 
    http://msdn.microsoft.com/zh-cn/library/system.runtime.interopservices.marshal.unsafeaddrofpinnedarrayelement(v=VS.80).aspx
      

  3.   

    依然没搞定,还是上源码吧
    java中代码
    package com.wt;public class Test {

    public String returnString(){
    return " hello Wt";
    }
    //此函数传入String类型,在c#中是ok的
    public String returnString(String s){
    return s;

    }
    //这个函数需要传入byte[]类型
    public String returnByte(byte[] bb){
    StringBuffer buffer = new StringBuffer();
    for(int i=0;i<bb.length;i++){
    buffer.append(Byte.toString(bb[i]));
    }
    return bb.toString();
    }

    public static void main(String[] args){
    byte[] bb = new byte[]{1,3,4};
    Test t = new Test();
    System.out.println(t.returnByte(bb));
    }}C#代码
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Text;
    using System.Windows.Forms;
    //引用java中的类
    using com.wt;
    using System.Runtime.InteropServices;namespace WindowsApplication1
    {
        
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }        private void button1_Click(object sender, EventArgs e)
            {  
                byte[] bytes = new byte[64];
                //创建IntPtr
                IntPtr buff = Marshal.UnsafeAddrOfPinnedArrayElement(bytes, 0); //取数组索引为0的元素的地址  
                //创建java对象
                Test tt = new Test();
                //此处调用java中returnByte方法,传入IntPtr类型参数
                MessageBox.Show(tt.returnByte(buff));
            }
        }
    }
    运行时错误信息:
    错误1 与“com.wt.Test.returnByte(byte[])”最匹配的重载方法具有一些无效参数
    错误2 参数“1”: 无法从“System.IntPtr”转换为“byte[]” 是否我的代码存在问题,请帮忙看下,谢了
      

  4.   

     MessageBox.Show(tt.returnByte(bytes));returnByte的参数就是byte[]不用取地址
      

  5.   

    感谢xingyuebuyu的答复,
    我用MessageBox.Show(tt.returnByte(bytes));测试通过,调用java中returnByte方法成功,
    但是还有个问题,我定义的byte[]作为参数传入java的returnByte函数是没问题,
    但我实际想传入的参数是SByte[],如果传入Byte[]类型参数,会提示与“com.wt.Test.returnByte(byte[])”最匹配的重载方法具有一些无效参数 如果传字节数据不成,我就想想别的办法了,改成别的类型试试了。
      

  6.   

    现在在学习C#,不过java出身,问下2楼是不是因为java是值传递造成楼主的错误。