tags:

views:

295

answers:

4

Hi,

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!

A: 

For pointers, what you want to use is IntPtr.

[DllImport("whatever.dll")]
static extern void init(IntPtr initData, IntPtr key);
Hawker
A: 

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

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

EvilPettingZoo42
Won't work properly here as the data almost certainly represents arrays instead of single values
JaredPar
You're right, they're arrays. For instance, the first parameter in the second function, inOut, is usually 8 bytes long.
alex
Actually you can pass an array to a ref param: "ref a[0]" - this pins the array and gives the address of the first item to the C function.
Daniel Earwicker
+5  A: 

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?
JaredPar
Yes, the return of encrypt is allocated memory. Normally, the size of the returned data is known (8 bytes).The parameters that are important are inOut and secretKey. Basically, you just use a for that goes from 0 to the size indicated by inputSize or secretKeySize to read all the data from the arrays.
alex
+2  A: 
[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);
Gerald
Wow!Thanks for all your help! It's really a great thing to have such a supportive community!
alex