C# 调用 C++ 写的Dll 遇到的问题(调用DLL 自动退出) win32已停止工作

来源:互联网 发布:js隐藏style没有定义 编辑:程序博客网 时间:2024/05/15 05:33
1 回调函数正确调用一次之后,程序自动
在回调函数前面加     [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[5] =0;
转到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=pVoid
   
   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

阅读全文
0 0
原创粉丝点击