Problem passing structs to dll's

G

Guest

Hi!

I am confused about the abnormal behaviour of my project.

Please consider the following situation:
I have written an application in C++.NET 2003 (managed) which loads and
executes an unmanaged function from an unmanaged dll.

On the dll-side i export this function:


typedef struct {
int a;
int b;...} mystruct;

__declspec(dllexport) int dllfn(mystruct* x);


Ok.
This all compiles (and also executes, I can test this via logfiles, etc).
BUT:
If I assign values to the given struct, they "do not arrive" in the main
(managed) application!!!

So, something like


x->a=17;


in the dll surprisingly does not set the value to 17 in the "real" struct
allociated in the main application. On the other hand, the same instruction
in the dll with


x->a=17; printf("a: %ld", x->a);


Works!!!

I do not have any idea, why I apparently do not have access to the struct I
want.


PLEASE HELP ME!

Thank you very much for your great help in advance!!!!

Kind regards!
 
G

Guest

Another question:
Do I have to export the definition of this struct explicitly, or is it
enough to just define the same struct in both the dll and the client
application?

Thanks in advance!
 
B

Ben Voigt

olidem said:
My general question:

Is is correct code to call a (extern dll) function with the adress of an
local structure ?
So, in the managed vc++ .net program:

in header file:

typedef struct {
int a;
int b;...} mystruct;

__declspec(dllimport) int dllfn(mystruct* x);

an in cpp file:

main(){
mystruct foo;
int bar;

bar = dllfn(&foo);
}

Is this doable?
Remember that the dll is unmanaged and even ANSI C compatible.

Yes, that should work. You have a native struct (not ref class or value
class), so the binary layout is compatible as long as the same packing is
used (controlled with pragma pack).
 
G

Guest

Hi Ben!
I tryed your hint, using #pragma pack (show) and got in BOTH, the native and
the managed, program the same following result:

warning C4810: value of pragma pack(show) == 8

It is as if the struct would be cleaned up by the gc if the dll-function
returns.
I also allocated the struct on the heap and gave a pointer to this adress in
the heap to the dll, with the same result.


An intersting observation:
If I assign a special value to one struct member in the managed client app,

foo.a = 815;

Then this 815 is visible in the dll. But if I change this in the dll to,
let's say 816, it does not arrive in the client again. But after the
816-assignment in the dll, this variable is really set to 816, I can work
with it.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top