3

假设我的 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;
4

3 回答 3

2

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

(我将return使用新结构,因为它更容易,但如果需要,可以使用 . 参数将其传递出去void** data。)

您可以像这样调用函数:

SampleStruct *strcc = TestFunction(type);
// do something with the struct
delete strcc;

不要忘记删除指针,否则会泄漏内存。您应该明确决定释放内存、调用者或 DLL 的责任。

于 2012-08-10T15:57:26.813 回答
0

您可以将功能更改为

void *func(int,void *) 

并返回新结构 - 但请注意,它必须使用 new 或 malloc 在堆上分配,然后由调用者使用 free 或 delete 释放

顺便说一句,默认赋值运算符不做你需要的吗?

sampleStruct newStruct;
sampleStruct *tmp=(sampleStruct *)data;
*tmp=newStruct;
于 2012-08-10T15:41:23.340 回答
-1

你是用c还是c++编码?

第一:如果你想这样调用函数:

SampleStruct strc;
TestFunction(DT_SS, &strc);

你不能。替换是什么意思&strc?您正在尝试替换结构的地址?那没有任何意义。同样在你不使用的c++中void *,你使用SampleStruct *

如果你想替换一些东西,你必须这样称呼它:

SampleStruct strc;
SampleStruct * pstrc = & strc;
TestFunction(DT_SS, pstrc);

现在你可以用你的结果替换 pstrc,如果你像这样编写你的函数:

void TestFunction(int type, SampleStruct * & data)

注意&,这意味着您将指针数据作为参考传递。现在你可以写data = & dllstrcc;了,它会修改pstrc,因为data不是变量,而是对 的引用pstrc。但是您可能想在尝试之前了解内存处理和内存泄漏。

于 2012-08-10T16:43:03.377 回答