Does P/Invoke work against C++ classes?

  • Thread starter Tommy Svensson \(InfoGrafix\)
  • Start date
T

Tommy Svensson \(InfoGrafix\)

Hi,

Can I use P/Invoke to obtain a C++ class type contained in a dll? I know how
to get structs and how to pass classes as parameters to native code but how
do I get C++ unmanaged classes from a native dll using P/Invoke?

Thx!

/Tommy
 
G

Guest

--
Kapil Khosla, Visual C++ Team
This posting is provided AS IS with no warranties, and confers no rights


Tommy Svensson (InfoGrafix) said:
Hi,

Can I use P/Invoke to obtain a C++ class type contained in a dll? I know how
to get structs and how to pass classes as parameters to native code but how
do I get C++ unmanaged classes from a native dll using P/Invoke?

Thx!

/Tommy

Sure you can. You can do PInvoke in two ways, explicit PInvoke and C++
interop.
You would use the explicit PInvoke when you have the source code for the
assembly available. The C++ interop or the implicit PInvoke will have to be
used if you dont have the source code available.

For documentation, please look into
http://msdn2.microsoft.com/library/2x8kf7zx(en-us,vs.80).aspx

I have added an example of explicit Pinvoke,

//native.cpp
#include <stdio.h>
class __declspec(dllexport) Native
{
public:
void foo()
{
printf("Native foo called");
}
};



//managed.cpp

using namespace System;

class __declspec(dllimport) Native
{
public:
void foo();
};

int main()
{
Native obj;
obj.foo();
}

cl /LD native.cpp
cl /clr managedcpp.cpp /link native.lib


Foo called.

Thanks,
Kapil
 

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