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. Any idea of what I am doing wrong?
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");
I've also tried other things like IntPtr and marshalling across the string but all turns out the same with 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.
However, in C# a long is always 64 bits.
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++.
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.
Change the declaration to int
instead of long
to solve your problem.
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));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.