问题描述
如何在Delphi中使用Unicode PWideChar来在DLL中调用C ++函数?我想将一个字符串从Delphi发送到C ++并进行修改.
How can I use a Unicode PWideChar in Delphi to call a C++ function in a DLL? I want to send a string from Delphi to C++ and modify it.
function Test(a: PWideChar): Integer; cdecl; external 'c:\Win32Project1.dll' name 'Test';
extern "C" __declspec(dllexport) int __cdecl Test(char* a)
{
a = "汉语";
return 0;
}
推荐答案
通常,调用方分配一个缓冲区,该缓冲区与缓冲区长度一起传递给被调用方.然后,被调用者填充缓冲区.
Typically the caller allocates a buffer which is passed to the callee, along with the buffer length. The callee then populates the buffer.
size_t Test(wchar_t* buff, const size_t len)
{
const std::wstring str = ...;
if (buff != nullptr)
wcsncpy(buff, str.c_str(), len);
return str.size()+1; // the length required to copy the string
}
在Delphi方面,您可以这样称呼它:
On the Delphi side you would call it like this:
function Test(buff: PWideChar; len: size_t): size_t; cdecl; external "mydll.dll";
....
var
buff: array [0..255] of WideChar;
s: string;
....
Test(buff, Length(buff));
s := buff;
如果您不想分配固定长度的缓冲区,则可以调用该函数以找出需要多大的缓冲区:
If you don't want to allocate a fixed length buffer, then you call the function to find out how large a buffer is needed:
var
s: string;
len: size_t;
....
len := Test(nil, 0);
SetLength(s, len-1);
Test(PWideChar(s), len);
如果希望将值传递给函数,建议您通过其他参数来实现.这样可以更方便地调用,并且不会强制您确保输入字符串的缓冲区足够大以容纳输出字符串.也许是这样的:
If you wish to pass a value to the function, I suggest that you do that through a different parameter. That makes it more convenient to call, and does not force you to make sure that the input string has a buffer large enough to admit the output string. Maybe like this:
size_t Test(const wchar_t* input, wchar_t* output, const size_t outlen)
{
const std::wstring inputStr = input;
const std::wstring outputStr = foo(inputStr);
if (buff != nullptr)
wcsncpy(buff, outputStr.c_str(), len);
return outputStr.size()+1; // the length required to copy the string
}
另一方面,应该是
function Test(input, output: PWideChar; outlen: size_t): size_t; cdecl;
external "mydll.dll";
调用代码应该很明显.
这篇关于如何在C ++ DLL中使用来自Delphi的Unicode的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!