tags:

views:

110

answers:

2

I am just wondering if it is possible to P/Invoke a pure C++ library, or does it have to be wrapped in C?

+1  A: 

A "pure" C++ library will have its name mangled by the compiler, so it will be hard to get the P/Invoke declaration correct. And a C method gets an underscore at the beginning, which may not be there in C++. And a C++ method needs a this instance as a first parameter, you'd have to give it yourself.

I think that you need to wrap your C++ API in a C-compatible series of methods.

Timores
Only an instance method of an object takes an implicit `this`.
280Z28
Of course, but I can't imagine a C++ library using only static methods.
Timores
@Timores: C++ allows non-member methods too, you know.
jalf
@jalf, yes, I agree with you, as well as with 280Z28. But, and I apologize for insisting, can you imagine writing a C++ library and using only non-member methods ?
Timores
@Timores: Yes. I can imagine a C++ library which uses member methods internally, but whose public interface is all non-member functions. Still, I agree with your point: Typical C++ libraries do expose member methods are part of their interface.
jalf
+2  A: 

C++ libraries can be P/invoked, but you'll need to use "depends" to find the mangled method names (names like "@0!classname@classname@zz") and for instance methods use "ThisCall" calling convention in the p/invoke and pass the reference of the instance as the first argument (you can store the result of the constructor within an IntPtr).

Danny Varod
Another alternative is C++/CLI.
Danny Varod