简体   繁体   English

将struct传递给dll

[英]passing struct to a dll

I want to pass several data to a Dll function, so I am thinking of creating a struct and passing them to Dll dunction via a struct such as follow: 我想将几个数据传递给Dll函数,所以我想创建一个结构并通过如下结构将它们传递给Dll dunction:

struct options
{
int op1,
int op2,
int op3,
char * op4,
...
char * op10
}

 void dllFunction(options myOptions)

As the dll should be implemented in a way that works on windows platform irrespective of what is the development tools is it, I am wondering : 由于dll应该以适用于Windows平台的方式实现,而不管它是什么开发工具,我想知道:

Is it valid to send data in this way? 以这种方式发送数据是否有效? note that the structure members all are basic c types (int, float, double, ...). 请注意,结构成员都是基本的c类型(int,float,double,...)。

Why I am worried about it? 为什么我担心呢? as you know, different compilers implemented std classes differently, so you can not pass std classes over dll boundaries, but I am not sure if all of the compilers are placing struct members in the same way or they are not, as if they are not, then the code may not work with some compilers. 如你所知,不同的编译器以不同的方式实现了std类,所以你不能通过dll边界传递std类,但是我不确定所有编译器是否以相同的方式放置struct成员或者它们不是,就好像它们不是,那么代码可能无法与某些编译器一起使用。

is a struct is a simple c type data type? struct是一个简单的c类型数据类型?

If I can not use a struct for this purpose, what is the best way to do this (passing a lot of data to a function inside a dll function? 如果我不能为此目的使用结构,那么最好的方法是什么(将大量数据传递给dll函数内的函数?

The C ABI is well-defined and stable, so this works fine. C ABI定义明确且稳定,因此工作正常。 To ensure that you are getting that C ABI if you are compiling as C++, you will need to annotate with extern "C" . 如果要编译为C ++,要确保获得C ABI,则需要使用extern "C"进行注释。

The only thing you'll have trouble with is pointers to memory. 你唯一遇到麻烦的就是内存指针。 Since there is no guarantee that the application and the DLL are using compatible run-time libraries, the code that allocated the memory must always be the one that frees it. 由于无法保证应用程序和DLL使用兼容的运行时库,因此分配内存的代码必须始终是释放它的代码。 You cannot have, for example, the application malloc a buffer, pass a pointer to that buffer to the DLL, and then expect the DLL to free the buffer. 例如,你不能让应用程序malloc成为缓冲区,将指向该缓冲区的指针传递给DLL,然后期望DLL free缓冲区。 Either the application needs to free the buffer (since it's the one that called malloc ), or the application will need to export a MyFree function that the DLL will call to free the memory. 应用程序需要free缓冲区(因为它是调用malloc的缓冲区),或者应用程序需要导出DLL将调用以释放内存的MyFree函数。

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

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