简体   繁体   English

使用dllimport收到的空指针[MSVS C ++ 2010]

[英]Using void pointer received by dllimport [MSVS C++ 2010]

I need to write a DLL (with MSVS 2010 PS1) that calls a function exported from exe: 我需要编写一个DLL(使用MSVS 2010 PS1),该DLL调用从exe导出的函数:

(dll.h):  extern "C" __declspec(dllimport) void*  __stdcall SomeFunction();

The problem is that void pointer can point to any datatype, and exe developers do not provide any guidelines on how to use this function. 问题在于,void指针可以指向任何数据类型,并且exe开发人员未提供有关如何使用此功能的任何指导。 Luckily exe project is opensource and I can see that SomeFunction actually returns a pointer to a structure, which is declared in structures.h file, which is used to compile exe: 幸运的是,exe项目是开源的,我可以看到SomeFunction实际上返回了一个指向结构的指针,该结构在structures.h文件中声明,该文件用于编译exe:

struct exeStructure {int    useme;  int usecallback; <...> };
  1. How do I use this information to set usecallback variable from DLL? 如何使用此信息从DLL设置usecallback变量? Could you please give an example? 你能举个例子吗?
  2. How should I dereference void* SomeFunction into exeStructure? 我应该如何将void * SomeFunction取消引用到exeStructure?
  3. Do I need to copy and include structures.h file in my DLL project? 我是否需要复制DLL项目并将其包含在DLL项目中?

You should assign the value of the void * to an exeStructure * type. 您应该将void *的值分配给exeStructure *类型。

You can do that via static_cast (better): 您可以通过static_cast(更好)来做到这一点:

exeStructure * exeStrPtr = static_cast<exeStructure*>(voidPtr);

Or via C-style cast (essentially the same in effect for this purpose, but not advised) : 或通过C样式强制转换(为此目的实际上是相同的,但不建议这样做):

exeStructure * exeStrPtr = (exeStructure *)voidPtr;

Then you can use the proper pointer as you would expect. 然后,您可以按照预期使用适当的指针。

exeStrPtr->usecallback = 1;
exeStrPtr->useme = 334;

For more details on the difference between the most common types of casting in C++ refer to this question : 有关C ++中最常见的类型转换之间的区别的更多详细信息,请参考以下问题

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

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