gpt4 book ai didi

delphi - 如何在 C++ DLL 中使用 Delphi 中的 Unicode

转载 作者:行者123 更新时间:2023-12-02 02:17:48 25 4
gpt4 key购买 nike

如何在 Delphi 中使用 Unicode PWideChar 来调用 DLL 中的 C++ 函数?我想从 Delphi 发送一个字符串到 C++ 并修改它。

function Test(a: PWideChar): Integer; cdecl; external 'c:\Win32Project1.dll' name 'Test';

extern "C" __declspec(dllexport) int __cdecl Test(char* a)
{
a = "汉语";
return 0;
}

最佳答案

通常,调用者分配一个缓冲区,该缓冲区连同缓冲区长度一起传递给被调用者。然后被调用者填充缓冲区。

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 方面,您可以这样调用它:

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;

如果你不想分配固定长度的缓冲区,那么你可以调用该函数来找出需要多大的缓冲区:

var 
s: string;
len: size_t;
....
len := Test(nil, 0);
SetLength(s, len-1);
Test(PWideChar(s), len);

如果您希望向函数传递值,我建议您通过不同的参数来实现。这使得调用更加方便,并且不会强制您确保输入字符串有足够大的缓冲区来容纳输出字符串。也许是这样的:

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";

并且调用代码应该是显而易见的。

关于delphi - 如何在 C++ DLL 中使用 Delphi 中的 Unicode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21867113/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com