将 .NET 4.0 与 dll 一起使用时出现未知错误
Unknown error when using .NET 4.0 with dll
c++ 代码是
MSIPC_SDK LONG __stdcall Ms_IpcClient_CaptureImage(LONG nUserId, char *sFilePath,
int nPathLen, const char *sDiskPath = NULL);//sDiskPath example: "C: \".
影响:拍一张快照
参数备注:
LONG nUserId
: Ms_Ipc_Login()//Return登录成功后的值
char *sFilePath
: //录音文件保存位置
int nPathLen
: //路径的长度
const char *sDiskPath = NULL
: //保存到哪个磁盘
我的 C# 代码是:
[DllImport("MsIpcSDK", CharSet = CharSet.Ansi,
CallingConvention = CallingConvention.StdCall)]
public static extern int Ms_IpcClient_CaptureImage(
int lUserID,
[MarshalAs(UnmanagedType.LPStr)]
string sFilePath,
int nPathLen,
[MarshalAs(UnmanagedType.LPStr)]
string sDiskPath
);
并使用方法:
var ret = Ms_IpcClient_CaptureImage(loginID, "C:\a.bmp", 10000, "C:\");
它在 .Net Framework 2 中工作,但在 .Net Framework 4 中不工作。
我如何在 .Net Framework 4 中修复它?
sFilePath
用于将字符串从被调用方传递给调用方。这就是为什么类型是 char*
而不是 const char*
的原因,这就是为什么有缓冲区长度参数的原因。这意味着您需要使用 StringBuilder
而不是 string
。 p/invoke 应该是:
[DllImport("MsIpcSDK", CharSet = CharSet.Ansi,
CallingConvention = CallingConvention.StdCall)]
public static extern int Ms_IpcClient_CaptureImage(
int lUserID,
StringBuilder sFilePath,
int nPathLen,
string sDiskPath
);
调用应该是:
var filePath = new StringBuilder(260);
var ret = Ms_IpcClient_CaptureImage(loginID, filePath, filePath.Capacity, "C:\");
您的代码一直都是错误的,直到现在您才侥幸逃脱。您传递了 10000
的组成缓冲区长度值这一事实应该已经敲响了警钟!
c++ 代码是
MSIPC_SDK LONG __stdcall Ms_IpcClient_CaptureImage(LONG nUserId, char *sFilePath,
int nPathLen, const char *sDiskPath = NULL);//sDiskPath example: "C: \".
影响:拍一张快照
参数备注:
LONG nUserId
: Ms_Ipc_Login()//Return登录成功后的值char *sFilePath
: //录音文件保存位置int nPathLen
: //路径的长度const char *sDiskPath = NULL
: //保存到哪个磁盘
我的 C# 代码是:
[DllImport("MsIpcSDK", CharSet = CharSet.Ansi,
CallingConvention = CallingConvention.StdCall)]
public static extern int Ms_IpcClient_CaptureImage(
int lUserID,
[MarshalAs(UnmanagedType.LPStr)]
string sFilePath,
int nPathLen,
[MarshalAs(UnmanagedType.LPStr)]
string sDiskPath
);
并使用方法:
var ret = Ms_IpcClient_CaptureImage(loginID, "C:\a.bmp", 10000, "C:\");
它在 .Net Framework 2 中工作,但在 .Net Framework 4 中不工作。 我如何在 .Net Framework 4 中修复它?
sFilePath
用于将字符串从被调用方传递给调用方。这就是为什么类型是 char*
而不是 const char*
的原因,这就是为什么有缓冲区长度参数的原因。这意味着您需要使用 StringBuilder
而不是 string
。 p/invoke 应该是:
[DllImport("MsIpcSDK", CharSet = CharSet.Ansi,
CallingConvention = CallingConvention.StdCall)]
public static extern int Ms_IpcClient_CaptureImage(
int lUserID,
StringBuilder sFilePath,
int nPathLen,
string sDiskPath
);
调用应该是:
var filePath = new StringBuilder(260);
var ret = Ms_IpcClient_CaptureImage(loginID, filePath, filePath.Capacity, "C:\");
您的代码一直都是错误的,直到现在您才侥幸逃脱。您传递了 10000
的组成缓冲区长度值这一事实应该已经敲响了警钟!