How to make a native API to be PInvoke friendly?
there are some tips on how to modify native-programs to be used with P/Invoke here. But before I even write a native programs, what are the things I should look out to make my programs/library PInvoke friendly?
using C or C++ are fine.
update:
if I write a C API, what are the things I have to do so that It is P/Invoke-able using C# syntax like the following:
[DLLimport("MyDLL.dll")]
is it possible to do the same with native C++ code/library?
Summary/Rephrase of Some Tips to make a P/Invoke friendly native-API:
+ the parameters should be of native types (int, char*, float, …)
+ less parameters is better
+ if dynamic memory is allocated and passed to managed code, make sure to create a “cleaner” function which is also p/invoked
+ provide samples and/or unit tests that illustrate how to call the API from .NET
+ provide C++/CLI wrapper
By definition every native function can be p/invoked from managed code. But in order to be p/invoke friendly a function should have as few parameters as possible which should be of native types (int, char*, float, …). Also if a function allocates memory on some pointer that is returned to managed code, make sure you write its counter part that will free the pointer as managed code cannot free memory allocated from unmanaged code.