简体   繁体   English

跨DLL投射void指针

[英]casting void pointer across dll

In a dll, I'm doing 在dll中,我正在执行

std::vector<foo*>* v = new std::vector<foo*>();
foo* f = new foo();
v->push_back(f);
// size of v is 1
process->Result = static_cast<void*>(v);  // Result is of type void*

and in a exe that uses the dll, I do 在使用dll的exe中,

if (process->Result != NULL)
{
   std::vector<foo*>* v = static_cast<std::vector<foo*>*>(process->Result);
   int size = v->size(); // <-- size is garbage (221232 or something like that)   

}

Result has to be a void* . 结果必须为void* Does anyone know why I'm not able to pass back the vector properly ? 有谁知道为什么我无法正确传回向量? Am I doing something wrong with the casting? 我在投放时做错了吗?

Thanks 谢谢

Because the standard library data structures such as std::vector are implemented in header files, the actual data representation can be different between versions of the compiler. 由于标准库数据结构(例如std::vector是在头文件中实现的,因此实际的数据表示形式在编译器的版本之间可能会有所不同。 If you have some code compiled with VS2005 and other code with VS2010, you cannot reliably return a std::vector in this way. 如果您有一些用VS2005编译的代码和其他用VS2010编译的代码,则无法以这种方式可靠地返回std::vector

Assuming foo is the exact same data layout between components, you could return an array of raw foo* pointers that has been allocated with HeapAlloc . 假设foo是组件之间的数据布局完全相同,则可以返回已由HeapAlloc分配的原始foo*指针的数组。 Do not use malloc() because again, your components are using different runtime libraries and you can't free() something that has been allocated with a different allocator. 不要使用malloc()因为同样,您的组件使用的是不同的运行时库,并且您无法free()已由其他分配器分配的内容。 By using HeapAlloc and HeapFree , you are using the Win32 standard allocator which is shared across your whole process. 通过使用HeapAllocHeapFree ,您将使用在整个过程中共享的Win32标准分配器。

By way of example, you could do something like: 举例来说,您可以执行以下操作:

v->push_back(f);
HANDLE heap = GetProcessHeap();
foo **r = (foo **)HeapAlloc(heap, 0, (v->size() + 1) * sizeof(foo *));
std::copy(v.begin(), v.end(), r);
r[v->size()] = NULL; // add a sentinel so you know where the end of the array is
process->Result = r;

and then in your calling module: 然后在您的调用模块中:

foo **v = static_cast<foo**>(process->Result);
for (int i = 0; v[i] != NULL; i++) {
    printf("index %d value %p\n", i, v[i]);
}
HANDLE heap = GetProcessHeap();
HeapFree(heap, 0, v);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM