buzjwa
buzjwa

Reputation: 2652

Calling a native function from managed code

I have a managed C++/CLI project which must use some native code. A simplified version of the native header file would be:

struct structA
{
   // Some variables...
};
struct structB
{
   // Some similar variables...
   void convertTo(structA& dest);
};

This header is included in the managed code. The managed code has:

structA sA;
structB sB;
// Load data into sB...
sB.convertTo(sA);

I am using Visual Studio 2008 and compiling the managed code with /clr. This of course generates a linker error (LNK2028), as the implicit calling conventions differ. However I have been unable to use extern "C" declarations to solve this (or perhaps I'm using them wrong). I have tried several of the solutions provided to similar questions here, to no avail.

How do I correctly call the unmanaged function from the managed code? What declaration or wrapper is required here?

Upvotes: 0

Views: 564

Answers (1)

buzjwa
buzjwa

Reputation: 2652

Turns out this was not a managed-unmanaged clash issue. I simply forgot to declare the used function as exported, i.e.,

__declspec(dllexport) void convertTo(structA& dest);

The second, more general linker error (LNK2019) for an unreferenced function was what I should have been paying attention to. It is strange that a managed-unmanaged clash error (LNK2028) was thrown as well, since this is a more specialized error (which also threw me off track). As far as I know, this error should only have applied was I to use /clr:pure, as was suggested in the comments as well.

Upvotes: 1

Related Questions