我是 C#/.net 编程的新手。
我正在将 WPF 代码中的以下 C# 结构编组到非托管 C++ dll 中的 C++ 类。
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
public struct CallbackParams
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)]
public string displayName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)]
public string userName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)]
public string sipIdentity;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)]
public string sipProxyAddress;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)]
public string password;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)]
public string sipurl;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)]
public string calleeURI;
[MarshalAs(UnmanagedType.U4)]
public UInt32 releaseCallId;
[MarshalAs(UnmanagedType.U4)]
public UInt32 answerCallId;
[MarshalAs(UnmanagedType.U4)]
public UInt32 answerCode;
[MarshalAs(UnmanagedType.U4)]
public UInt32 timeout;
[MarshalAs(UnmanagedType.U4)]
public UInt32 rate_percent;
}
C++ 类看起来像这样
typedef struct CallbackParams_s {
char displayName[80];
char userName[80];
char sipIdentity[80];
char sipProxyAddress[80];
char password[80];
char sipurl[80];
char calleeURI[80];
unsigned int releaseCallId;
unsigned int answerCallId;
unsigned int answerCode;
unsigned int timeout;
unsigned int rate_percent;
} CallbackParams;
在 C# 代码中
public CallbackParams cb;
public int code;
[DllImport("XXXDll.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
public static extern int DLLCBFunc1([MarshalAs(UnmanagedType.I4)] int someCode, ref CallbackParams cbParams);
cb.displayName = "XYZ";
... ...
... ...
...Init other fields in struct ....
...
cb.calleeURI = "ABC";
code = 0;
DLLCBFunc1(code, ref cb);
在上述调用中,cb 结构被正确编组到非托管 dll。现在,
cb.calleeURI = "DEF";
code = 1;
DLLCBFunc1(code, ref cb);
当再次调用 DLLCBFunc1 时,代码参数在非托管 dll 中被正确编组,但 cb.calleeURI 仍设置为比“DEF”更早的“ABC”。
我错过了什么?
感谢你的帮助。
EDIT:
Edited to provide more code
C++ code
Class MyClass {
...
...
public:
void SetCBParams(CallbackParams *cb) { cbParams = cb };
private:
CallbackParams *cbParams;
}
MyClass *m_class;
extern "C" __declspec(dllexport) int DLLCBFunc1(int code, CallbackParams *cb)
{
if(code == 0) {
m_class = new MyClass;
}
m_class->setCBParams(cb);
....
..call some func ...
}