tags:

views:

42

answers:

1

Hey guys, I'm creating a DLL in C++ and I want it to be usable from .NET apps (both C# and VB.NET). I've been scouring the internet for tips and what I've found so far suggests:

  • Declaring my C++ functions as extern C and using __stdcall
  • Using basic C types for parameters and return types instead of STL containers (e.g. char* instead of std::string)
  • Using pointers for input parameters that need to be modified instead of references

Assuming typedef unsigned char byte;

It's a compression function. The inputs it expects are the input data (passed as byte*), the size of the input data (passed as int), a pointer to the variable in which to store the compressed size (passed as int*), and a string in which error messages can be stored if needed (passed as char*). The function malloc's the output buffer, writes the output, and returns a byte*, and the calling code is expected to free the buffer when it's done using it. In case an error occurs the error message is strcpy'd into the error string and a NULL pointer is returned.

Is my current set-up all right or do I need to make some other modifications for it to be callable from .NET?

+2  A: 

The managed code cannot free the memory, it doesn't have access to the allocator built into the CRT. You could use CoTaskMemAlloc() to allocate the buffer instead, the managed code can call Marshal.FreeCoTaskMem(). You'd have to declare the buffer pointer argument as "ref IntPtr" or declare the return type of the function as IntPtr. Which gives the managed code the hassle of converting it to a managed byte array.

This is not pretty, these problems disappear when you write the code in C++/CLI or write a COM server.

Hans Passant
Yep, C++/CLI is the way go.
Brian Gideon