C# 呼叫 C++ 寫的Dll 遇到的問題(呼叫DLL 自動退出) win32已停止工作
在回撥函式前面加 [UnmanagedFunctionPointer(CallingConvention.Cdecl)] 進行修飾
如下所示:
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate void RecivecallBack(IntPtr pVoid, string mydata, int lend, int msg, int pNo);
2. 回撥函式裡面 const char * 指標轉到 c# 的 string ,BYTE位元組流丟失問題,如char test[]="01234\12345" test
轉到c# 的 string 就只有 "01234“。
C++ 程式碼:
myDll.h
typedef void (*RecivecallBack)(LPVOID pVoid, char *mydata,int mLen);
LPVOID m_void;
RecivecallBack m_function; //回撥函式
//註冊回撥函式
extern "C" __declspec(dllexport) void SetReceiveCallback(LPVOID pVoid,RecivecallBack function)
{
m_void
m_function =function ; //回撥函式
}
extern "C" char *g_source;
//拷貝 只有 輸出 dest是輸出介面 是C# 的傳入介面
extern "C" __declspec(dllexport) int MemcpyOut(char *dest,int length)
{
if ( g_source == NULL)
return 0;
memcpy(dest,g_source,length);
return length;
g_source =NULL;
}
/************************************************myDll.h of end
myDll.Cpp
回撥函式傳送函式
/*
本歷程將 將 test 傳給C# 的回撥函式。
*/
void test()
{
char test[]="01234\12345" ;test[5] =0;
int datLend =10;
//開始 呼叫回撥函式
g_source =test;//為了 C++ 轉 C# 不丟失資料
m_function(m_void,test,datLend);
}
/************************************************end of myDll.Cpp
of *****************************************/
C# 程式碼:
namespace MyDll.appLib
{
class MyDllApp
{
//拷貝函式
[DllImport("myDll.dll",
CallingConvention = CallingConvention.Cdecl)]
public static extern int MemcpyOut(byte[] dest, int leng);
//定義委託函式
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate void RecivecallBack(IntPtr pVoid, string mydata, int lend);//
[DllImport("myDll.dll",
SetLastError = true, CallingConvention = CallingConvention.Cdecl)]
static extern void SetReceiveCallback(IntPtr pVoid, RecivecallBack function);
public static RecivecallBack m_callback;
public static IntPtr mpVoid;
//註冊函式
public static void add(object pVoid, RecivecallBack callback)
{
m_callback = callback;
handle = GCHandle.Alloc(pVoid);
mpVoid = GCHandle.ToIntPtr(handle);
SetReceiveCallback(mpVoid, m_callback);
}
}
}
test:
回撥函式
public static void MyRecivecallBack(IntPtr pVoid, string byteArray,int lend)
{
Object obj = GCHandle.FromIntPtr(pVoid).Target;
UserTest temp = obj as UserTest;
byte[] newByte = new byte[lend];
ParkPushApp.MemcpyOut(newByte, lend); //拷貝來自 ParkPush 的資料
}
原文:http://blog.csdn.net/feiyang094/article/details/47297809
http://blog.csdn.net/snakorse/article/details/20749529