在C#中调用C的dll,遇到char* 使用 intPtr接收,返回值与C中char 指针不一致
C结构体
typedef struct
{
BYTE ErrCode;
int* errstring;
} ERRPARAMS;
函数
BYTE DSCUDAPICALL dscGetLastError(ERRPARAMS* errparams);
C#结构体
[StructLayout(LayoutKind.Sequential)]
public struct ERRPARAMS
{
public byte ErrCode;
public IntPtr errstring;
}
函数
[DllImport("dscud.dll", EntryPoint = "dscGetLastError", CharSet = CharSet.Unicode, SetLastError = false, CallingConvention = CallingConvention.Cdecl)]
extern unsafe public static byte dscGetLastError(ERRPARAMS* errparams);
执行结果:
在C中 ErrCode是5 errstring是0x1007eb80 可以转换成字符串
在C#中 ErrCode是5 errstring是0x00000010 使用Marshal.PtrToStringAnsi转换为空,不是想要的地址
将intPtr改成string/String/StringBuilder/char[]都试过了,函数会报内存异常的错误。
且大神解答,非常感谢。