假设我的 DLL 中有以下函数:
void TestFunction(int type, void* data)
现在从加载该 DLL 的应用程序调用该函数。应用程序初始化一个结构并将指向该结构的指针发送给该函数:
SampleStruct strc;
TestFunction(DT_SS, &ss);
到目前为止一切顺利。现在困扰我的是如何将内存中的strcc变量替换为另一个结构体。如果我在我的 dll 中执行以下操作:
SampleStruct dllstrcc;
data = &dllstrcc;
data 现在将指向新的 dllstrcc 结构,但是当它存在时函数和控制返回给应用程序 strc 仍将指向第一个结构。如何在不分配每个字段的情况下用 dll 中的结构替换应用程序的结构:
data.vara = dllstrcc.vara;
data.varb = dllstrcc.varb;
data.varc = dllstrcc.varc;
最佳答案
1.最简单的选择是复制整个结构:
void TestFunction(int type, void* data) {
SampleStruct dllstrcc;
// fill dllstrcc here...
SampleStruct *p_ret = data;
*p_ret = dllstrcc;
}
通过
调用它SampleStruct strcc;
TestFunction(type, &strcc);
好处是不用担心释放内存等问题
2。如果你真的想替换调用者的结构(有一个新的结构),你可以在DLL中分配一个新的结构。
void* TestFunction(int type) {
SampleStruct* pdllstrcc = new SampleStruct();
return pdllstrcc;
}
(我将返回
新结构,因为它更容易,但如果需要,您可以使用void**数据
通过参数将其传递出去。 )
您可以像这样调用该函数:
SampleStruct *strcc = TestFunction(type);
// do something with the struct
delete strcc;
不要忘记删除指针,否则会泄漏内存。您应该明确决定谁负责释放内存,是调用者的还是 DLL 的。
关于c++ - C/C++ - 指针传递给 DLL 中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11904888/