Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a C++ function from C#

Tags:

c++

c#

dll

I have 2 C++ DLLs. One of them contains the following function:

void init(const unsigned char* initData, const unsigned char* key)

The other one contains this function:

BYTE* encrypt(BYTE *inOut, UINT inputSize, BYTE *secretKey, UINT secretKeySize).

Is there a way to call these 2 functions from C#? I know you can use [DllImport] in C# to call C++ functions, but the pointers are giving me a hard time.

Any help would be appreciated!

like image 334
alex Avatar asked Oct 17 '25 01:10

alex


2 Answers

Yes, you can call both of these from C# assuming that they are wrapped in extern "C" sections. I can't give you a detailed PInvoke signature because I don't have enough information on how the various parameters are related but the following will work.

[DllImport("yourdllName.dll")]
public static extern void init(IntPtr initData, IntPtr key);

[DllImport("yourdllName.dll")]
public static extern IntPtr encrpyt(IntPtr inout, unsigned inuputSize, IntPtr key, unsigned secretKeySize);

Pieces of information that would allow us to create a better signature

  1. Is the return of encrypt allocated memory?
  2. If #1 is true, how is the memory allocated
  3. Can you give a basic description on how the parameters work?
  4. I'm guessing that all of the pointer values represents arrays / groups of elements instead of a single element correct?
like image 182
JaredPar Avatar answered Oct 18 '25 14:10

JaredPar


[DllImport("yourdll.dll")]
static extern void init([MarshalAs(UnmanagedType.LPArray)] byte[] initData, [MarshalAs(UnmanagedType.LPArray)] byte[] key);

[DllImport("yourdll.dll")]
static extern IntPtr encrypt([MarshalAs(UnmanagedType.LPArray)] byte[] inOut, int inputSize, [MarshalAs(UnmanagedType.LPArray)] byte[] key, int secretKeySize);
like image 43
Gerald Avatar answered Oct 18 '25 13:10

Gerald



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!