两个错误:1. Run-Time Check Failure #0 - The value of ESP was not properly saved across a function call. This is usually a result of calling a function declared with one calling convention with a function pointer declared with a different calling convention
先把dll的项目属性中C/C++->Code Generation(代码生成)->Basic Runtime Checks的属性改为Default
2. System.AccessViolationException: 尝试读取或写入受保护的内存。这通常指示其他内存已损坏。
查看一下你的dll中的函数,如果函数返回是采用某个局部变量,需要把这些返回的局部变量都声明为static
3. 注意事项 函数声明,两种语言都要保持一致
如 int __stdcall true_add(int x, int y)
C# 中 CallingConvention = CallingConvention.StdCall
4. 代码实例
Cpp:
#include <stdlib.h>
#include <stdio.h>
typedef int (*pfunc)(int, int);
pfunc myadd;
int testAdd(int a,int b);
int __stdcall add(pfunc add)
{
printf("helloworld \n");
myadd = add;
//myadd = testAdd;
//printf("%d \n",add(11,2));
return 2;
}
//int __stdcall true_add(int x, int y)
int __stdcall true_add(int x, int y)
{
if(myadd)
return myadd(x, y);
else
return 222;
}
int testAdd(int a,int b)
{
return a+b;
}
def:
LIBRARY
EXPORTS
add @1
true_add @2
testAdd @3
以上在win32 下生成dll
C#:
class MyTest
{
[DllImport(@"E:\WorkSpace\CPlusPlusCode\LearnTecknology\LearnDemoTest\Debug\TestLibrary3.dll")]
public static extern int testAdd(int a, int b);
[DllImport(@"E:\WorkSpace\CPlusPlusCode\LearnTecknology\LearnDemoTest\Debug\TestLibrary3.dll", EntryPoint = "add", SetLastError = true, CharSet = CharSet.Unicode, ExactSpelling = true,
CallingConvention = CallingConvention.StdCall)]
public static extern int add(pfunc f);
[DllImport(@"E:\WorkSpace\CPlusPlusCode\LearnTecknology\LearnDemoTest\Debug\TestLibrary3.dll", EntryPoint = "true_add", SetLastError = true, CharSet = CharSet.Unicode, ExactSpelling = true,
CallingConvention = CallingConvention.StdCall)]
public static extern int true_add(int a, int b);
public delegate int pfunc(int a, int b);
public int MyFunc(int a, int b)
{
return a + b - 10;
}
public static pfunc pf;
public MyTest()
{
try
{
pf = new pfunc(MyFunc);
int ret = add(pf);
Console.WriteLine("jjj=" + pf(22, 33) + " , ret=" + ret);
Console.WriteLine(true_add(22, 33));
//int a = testAdd(258, 22);
//Console.WriteLine(a.ToString());
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
}
// 另外C#调用C++一般出现的问题 可参考 /yun0216/item/f7c856d227465738e3108fa3