C ++ function call from C #

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

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

Another 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 that you can use [DllImport] in C # to call C ++ functions, but pointers give me a hard time.

Any help would be appreciated!

+3
source share
4 answers

Yes, you can call both from C #, assuming 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);

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

  • Is returning allocated memory for encryption?
  • # 1 ,
  • , ?
  • , / ?
+6
[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);
+2

For pointers, what you want to use is IntPtr .

[DllImport("whatever.dll")]
static extern void init(IntPtr initData, IntPtr key);
0
source

For classes you do not need to do anything special. For value types, you need to use the ref keyword.

There is an article on MSDN that summarizes this: http://msdn.microsoft.com/en-us/library/awbckfbz.aspx

0
source

Source: https://habr.com/ru/post/1710413/


All Articles