我有一个64位的C ++ dll,其中包含一个返回LPStr
的函数。我想在C#中调用此函数。函数声明如下:
__declspec(dllexport) LPSTR __stdcall function(int16_t error_code);
在我的C#代码中,我尝试了以下操作:
[DllImport(@"<PathToInterface.dll>", EntryPoint = "function")]
[return: MarshalAs(UnmanagedType.LPStr)]
public static extern string function(Int16 error_code);
然后在程序中:
string ErrorMessage = "";
ErrorMessage = function(-10210);
我知道该函数本身很好,因为我可以从另一个用LabVIEW FWIW编写的程序中调用它。但是,当我执行C#程序时,它以错误代码0x80000003
退出,我什至无法尝试捕获异常。
如何正确调用此函数?
作为副节点:我在此dll中确实具有其他功能,这些功能使用LPStr
作为参数,可以毫无问题地调用它。只有两个返回LPStr
的函数会出现问题
答案 0 :(得分:1)
如何正确调用此函数?
互操作吗?你不能...在纯C ++中它也容易出错
您应该宁愿像
extern "C" __declspec(dllexport) int __stdcall function(int16_t error_code,
LPSTR buffer, size_t size)
{
LPCSTR format = "error: %i";
size_t req = _scprintf(format, error_code); // check for require size
if (req > size) //buffer size is too small
{
return req; //return required size
}
sprintf_s(buffer, size, format, error_code); //fill buffer
return 0;
}
和用法
class Program
{
static void Main(string[] args)
{
short error_code = -10210;
var ret = function(error_code, null, 0); // check for required size of the buffer
var sb = new StringBuilder(ret); // create large enough buffer
ret = function(error_code, sb, (uint)sb.Capacity + 1); //call again
var error_desc = sb.ToString(); //get results
Console.WriteLine(error_desc);
Console.ReadKey();
}
[DllImport("TestDll.dll", EntryPoint = "function", CharSet = CharSet.Ansi)]
public static extern int function(short error_code, StringBuilder sb, int size);
}
在C ++中的用法
typedef int (__stdcall *function)(int16_t error_code, LPSTR buffer, size_t size);
int main()
{
auto handle = LoadLibrary(L"TestDll.dll");
auto proc = (function)GetProcAddress(handle, "_function@12");
// of course it can be done via linking
int16_t error_code = 333;
const int ret = proc(error_code, NULL, 0); // check for size
CHAR* buffer = new CHAR[ret + 1];
//CHAR buffer[200]; //eventually allocate on stack
//but size have to be constant value and may be too small
proc(error_code, buffer, ret+1); // call again
MessageBoxA(0, buffer, "Return", 0); //show result
delete[] buffer; //free buffer!
FreeLibrary(handle);
return 0;
}