Call a C++ function from C#

前端 未结 4 1010
醉梦人生
醉梦人生 2020-12-18 11:17

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

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

The othe

相关标签:
4条回答
  • 2020-12-18 12:00

    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?
    0 讨论(0)
  • 2020-12-18 12:07
    [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);
    
    0 讨论(0)
  • 2020-12-18 12:11

    For pointers, what you want to use is IntPtr.

    [DllImport("whatever.dll")]
    static extern void init(IntPtr initData, IntPtr key);
    
    0 讨论(0)
  • 2020-12-18 12:13

    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

    0 讨论(0)
提交回复
热议问题