简体   繁体   English

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

[英]C# calling an unmanaged C driver(dll)

I'm really not sure what I am doing wrong. 我真的不确定我做错了什么。 I am passing a string to my dll written in C from C# as lots of examples on the net state..for some reason the string is coming out as NULL in the C dll. 我正在将一个字符串传递给我用C#编写的Cll作为网络状态下的大量示例..由于某种原因,字符串在C dll中显示为NULL。 Any idea of what I am doing wrong? 我知道我做错了什么?

C: 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#: 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");

I've also tried other things like IntPtr and marshalling across the string but all turns out the same with NULL. 我还尝试过其他的东西,比如IntPtr和编组整个字符串,但所有结果都与NULL相同。 And also a bunch of other things. 还有一堆其他的东西。

In Microsoft C++ and C, on 32 and 64-bit builds a long is only 32 bits. 在Microsoft C ++和C中,在32位和64位构建上,long只有32位。

However, in C# a long is always 64 bits. 但是,在C#中,long总是64位。

So what I think is happening is that some of the bytes of the two 64 bit longs that are pushed onto the stack by the C# call are being popped off as the Data* in the C++. 所以我认为正在发生的是,C#调用被压入堆栈的两个64位长的一些字节被弹出作为C ++中的Data*

Because the second parameter you're pushing is 0, it so happens that bytes with value 0 are being used for the pointer, hence it is null. 因为您要推送的第二个参数是0,所以会发生值为0的字节用于指针,因此它为空。

Change the declaration to int instead of long to solve your problem. 将声明更改为int而不是long来解决您的问题。

Did you try the below option: 您是否尝试过以下选项:

    [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));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM