日期:2014-05-17  浏览次数:20864 次

c++ builder 封装了一个dll,c#调用报错,求助!!
cb的代码:
 __declspec(dllexport)  class TTest{     //声明导出类

public:
 int __stdcall sum(int x, int y);

};

//---------------------------------------
 int  _stdcall TTest::sum(int x, int y)     //类的实现
{
 return x + y;

}


c#调用:
      [DllImport("Project1.dll", EntryPoint = "sum", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
        public unsafe  static extern Int32 sum( ref int x,ref int y);

           System.Int32 j = 120, i = 1;
            Int32 jj = sum(ref i,ref j);
提示“对 PInvoke 函数 的调用导致堆栈不对称。原因可能是托管的 PInvoke 签名与非托管的目标签名不匹配。” 
jj的结果是个比较大的数字
c++ dll

------解决方案--------------------
public unsafe  static extern Int32 sum( ref int x,ref int y);
=>
public static extern int sum(int x,int y);
------解决方案--------------------
不好意思,之前看错了。

最好不要把类的成员函数直接导出。

你的代码最少有4个问题。

1 你的代码不需要ref,之前我说了
2 你的方法用的是stdcall,你却定义了CallingConvention.Cdecl
3 成员函数的参数其实比你定义的多一个,带一个this指针,但是C#没办法识别这个类型。你试试看
int sum(int x, int y, IntPtr thisptr)
4 你是成员函数,函数名不是sum,至于是什么,我不太清楚,看BCB的链接器怎么做的。