简体   繁体   中英

casting void pointer across dll

In a dll, I'm doing

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

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* . 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. If you have some code compiled with VS2005 and other code with VS2010, you cannot reliably return a std::vector in this way.

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 . 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. By using HeapAlloc and HeapFree , you are using the Win32 standard allocator which is shared across your whole process.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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