我之前问过一个关于 delphi 和 C/C++ DLL 的问题。
我现在有另一个关于记录/结构的问题。 DLL 应该能够从 MainAPP 动态更改指针变量的值。
我的delphi MAINAPP有如下记录:
type MyRec = record
MyInteger : Pointer;
MyWideString : pwidechar;
MyString : pchar;
MyBool : Pointer
end;
type
TMyFunc = function ( p : pointer ): pointer; stdcall;
procedure test;
var
MyFunction : TMyFunc;
TheRecord : MyRec;
AnInteger : Integer;
AWideString : WideString;
AString : String;
ABool : Bool;
begin
AnInteger := 1234;
AWideString := 'hello';
AString := 'hello2';
ABool := TRUE;
TheRecord.MyInteger := @AnInteger;
TheRecord.MyWideString := pwidechar(AWideString);
TheRecord.AString := pchar(AString);
TheRecord.ABool := @ABool;
[...]
@MyFunction := GetProcAddress...
[...]
MyFunction (@TheRecord); // now the DLL should be able to change the values dynamically.
MessageBoxW (0, pwidechar(AWideString), '', 0); // Show the results how the DLL changed the String to...
end;
C/C++代码(只是例子)
typedef struct _TestStruct{
void *TheInteger; // Pointer to Integer
wchar_t *TheWideString; // Pointer to WideString
char *TheAnsiString; // Pointer to AnsiString
bool *TheBool // Pointer to Bool
}TestStruct;
__declspec(dllexport) PVOID __stdcall MyExportedFunc (TestStruct *PTestStruct)
{
MessageBoxW(0 ,PTestStruct->TheWideString, L"Debug" , 0); // We read the value.
PTestStruct->TheWideString = L"Let me change the value here.";
return 0;
}
由于某些原因它崩溃等。 我做错了什么?
感谢您的帮助。
最佳答案
这可能不是 C++ 代码分配给 TheWideString
指针时崩溃的原因,但我确实看到了预期问题...
我注意到您将 Delphi AWideString
变量指向的字符串数据的地址放入记录的 MyWideString
字段中。您将记录传递给 C++ 函数,该函数将新的指针值分配给记录的 TheWideString/MyWideString
字段。当执行返回到 Delphi 代码时,您输出 AWideString
变量的内容。
您的评论表明您希望 C++ 函数更改 AWideString 变量的内容,但这不会发生。
C++ 函数更改结构中的字段。它对该字段先前指向的内存位置没有任何作用。 AWideString指向的数据不会受到C++函数的影响。
如果 C++ 代码将数据复制到字段中包含的地址,那么它将覆盖 AWideString
指向的字符串数据。由于 AWideString
是一个 Delphi 管理的字符串,并且 C++ 函数将比原始字符串分配的空间更多的数据复制到该字符串内存区域,在 C++ 函数中复制数据将写入到结束Delphi 分配的字符串缓冲区可能会损坏 Delphi 堆。一段时间后可能会发生崩溃。所以最好只将指针分配给字段,而不是复制数据! ;>
要查看 C++ 函数更改了什么,您的 Delphi 代码应在调用 C++ 函数后输出记录的 MyWideString
字段的内容。
关于c++ - Delphi 和 C/C++ DLL 结构与记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11732585/