Two errors:
1. Run-Time Check Failure #0-The value of ESP was not properly saved stored ss
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
First, change the C/C ++-> Code Generation (Code Generation)-> Basic Runtime Checks attribute in the dll project attribute to Default.
2. System. AccessViolationException: Try to read or write the protected memory. This usually indicates that other memory is damaged.
Check the functions in your dll. If the function returns a local variable, You need to declare all the returned local variables as static.
3. Note: The function declaration must be consistent between the two languages.
For example, int _ stdcall true_add (int x, int y)
C # CallingConvention = CallingConvention. StdCall
4. Code instance
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
The above dll is generated under win32
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 ());
}
}
}
// Other common problems with C # Calling C ++
See http://hi.baidu.com/yun0216/item/f7c856d227465738e3108fa3