views:

205

answers:

3

I've a old C/C++ class that i want to refactor and access from .net using PInvoke

All P/Invoke tutorials refers to call win32 api but i haven't found anything to code the other side

Any tips/ideas ? my c/c++ experience is pretty rusty :(

UPDATE - this is for wrapping existing C/C++ code so it can called from .net using P/Invoke

How do i define the C function so from .net i can get the value using ref/out strings

A: 

I believe C++/CLI is the preferred bridge between native and CLR code in the way you describe. P/Invoke is specifically intended for calling win32 apis.

http://msdn.microsoft.com/en-us/magazine/dd315414.aspx

Cogwheel - Matthew Orlando
Nah, P/Invoke works fine for your own code too.
Hans Passant
The same code signatures should work for my custom code too, no ?
Kumar
+1  A: 

The simplest way in my experience is to make your C++ class into a COM class (or create a helper class for this purpose) and then add a reference to it in your .NET project.

If you want to access the .NET object from C++ then the opposite is true, mark it as ComVisible and use tlbexp to create a TLB for the native code to import (then you can use it as a regular COM object).

Motti
making it com compatible would be way over my head This is essentially to read some custom binary data so pinvoke seems simplest if i can figure out how to return ref/out strings
Kumar
@Kumar, you don't have to make the whole class COM compatible, just create a little COM object with one function that calls this native function. Otherwise you can use P/Invoke, have you tried `[MarshalAs(UnmanagedType.LPStr)] out string s`?
Motti
I am a VC++ newbie, any pointers/samples on how to get that, nothing shows on google search for com compatible class etc.
Kumar
COM is the slowest form of interop and generally the most work on the native side. Not my first choice.
Kate Gregory
+1  A: 

Here you find help
C++ Interop
Walkthrough: Porting an Existing Native C++ Application to Interoperate with .NET Framework Components
Use Our ManWrap Library to Get the Best of .NET in Native C++ Code
How to call C++ code from Managed, and vice versa (Interop)

lsalamon
The 2nd link is good but stopped short of sample for how to get a reference to the string back to .net/managed code !!
Kumar