c#调用非托管C驱动程序(dll)

本文关键字:驱动程序 dll 调用 | 更新日期: 2023-09-27 18:17:25

我真的不知道我做错了什么。我正在传递一个字符串到我的dll从c#写在C作为网络状态上的很多例子..由于某种原因,字符串出来为NULL在C dll。知道我做错了什么吗?

C:

 extern __declspec(dllexport) void Cmd(long CmdType,long DataPar, const char *DataStr);
 void Cmd(long CmdType,long DataPar,const char *DataStr)
 {
     // DataStr is NULL here even when passing a string with data in it
 }
c#:

    [DllImport(@"pjsua-i386-Win32-vc8-Debug.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
    public static extern void Cmd(long CmdType, long DataPar,[MarshalAs(UnmanagedType.LPStr)]String s);
    Cmd(1,0,"TEST");

我也尝试过其他的东西,比如IntPtr和跨字符串的编组,但结果都是一样的NULL。还有其他一些东西

c#调用非托管C驱动程序(dll)

在Microsoft c++和C中,在32位和64位构建中,long只有32位。

然而,在c#中,long总是64位的。

所以我认为发生的事情是,c#调用推入堆栈的两个64位长数据中的一些字节在c++中作为Data*被弹出。

因为你压入的第二个参数是0,所以恰好值为0的字节被用于指针,因此它是空的。

将声明改为int而不是long来解决您的问题

您是否尝试了以下选项:

    [DllImport(@"pjsua-i386-Win32-vc8-Debug.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
    public static extern void Cmd(int CmdType, int DataPar,IntPtr s);
    Cmd(1,0,Marshal.StringToHGlobalAnsi(str));