Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unmanaged struct as return value to managed

I have a unmanaged third party library (C). I'm trying to write a wrapper in C++/CLI, so I can use the library from C#. I have several C examples, but I can't figure out how to bridge the unmanaged and managed heaps.

One of the functions in the library returns a struct, which I need to keep in my managed wrapper. This struct is then used as a parameter for other functions.

Working C-example:

library.h

typedef struct FOO_BAR_STRUCT* FOO_BAR;
DLLEXPORT FOO_BAR FooBarCreate();

Example.c

#include <library.h>

int main(int argc, char* argv[]) {
char* address = "127.0.0.1"; 
FOO_BAR fb = NULL;

fb = FooBarCreate();

FooBarRegister(fb, address);
}

So in my Wrapper, I try to recreate what the example do. I've figured out that the problem is which heap the struct is on, but I haven't been able to figure out how to solve this.

My C++ code, compiled as a C++/CLI .dll for use in my C# project.

FooBarComm.h

#include <library.h>

ref class FooBarComm
{
public:
    FooBarComm(char* address);
    ~FooBarComm();

private:
    FOO_BAR fb;
};

FooBarComm.cpp

#include "FooBarComm.h"

FooBarComm::FooBarComm(char* address)
{
    fb = FooBarCreate();
    FooBarRegister(fb, address);
}

FooBarComm::~FooBarComm()
{
}

And this fails. How can I get the instance of the FOO_BAR struct from the unmanaged code into the managed class, then use it as a argument in later functions.

Edit:

I fails with a warning LNK4248: unresolved typeref token (0100000D)
error LNK2028: unresolved token (0A00000A) "extern "C" struct FOO_BAR_STRUCT
error LNK2019: unresolved external symbol "extern "C" struct FOO_BAR_STRUCT

I guess the problem is that I don't have a definition of the FOO_BAR_STRUCT in any header files that came with the library. I'm starting to dislike this library.

Is it sensible to create a unmanaged class that holds the reference to the struct, and then reference this unmanaged class from a managed class?

If I change to a "normal" C++ class, I get a different compile error:

FooBarComm.h

#include <library.h>

#pragma unmanaged    
class FooBarComm {
...

I get the compile error:

error LNK2019: unresolved external symbol _FooBarCreate referenced

Edit 2:

Ofcourse it was a missing link to the .lib file.

like image 896
Håkon K. Olafsen Avatar asked Dec 04 '25 15:12

Håkon K. Olafsen


1 Answers

This looks awfully like a linker error caused by the omission of the .lib file for the 3rd party library. I expect that if you add that to your link options then your problems will be solved.

like image 178
David Heffernan Avatar answered Dec 06 '25 03:12

David Heffernan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!