Convert C++ dll exposed function from a C++ dll in C#

bioan 41 Reputation points
2021-09-26T14:04:48.62+00:00

Hi everybody!

I have the following C++ function signature:

unsigned int MyCPlusPlusFunction(IUnknown* document, unsigned int id, const wchar_t* name, IUnknown** ids, unsigned int* flags, unsigned int* size);

which I want to use inside a C# .dll library project using P/Invoke mechanism.

Can you direct me how to use it inside my C# code?

Thank you very much!

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,291 questions
C++
C++
A high-level, general-purpose programming language, created as an extension of the C programming language, that has object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation.
3,540 questions
0 comments No comments
{count} votes

Accepted answer
  1. RLWA32 40,756 Reputation points
    2021-09-27T12:57:30.883+00:00

    It appears that the caller is responsible for passing an array of IUnknown pointers and the number of elements in the array and the MyCPlusPlus function will fill the array and indicate the number of IUnknown pointers that were stored in the array.

    Give this a try to let the .Net handle the marshaling for you -

            [DllImport("ArrayMarshal.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Unicode)]
            static extern uint MyCPlusPlusFunction([MarshalAs(UnmanagedType.IUnknown)] object document, uint id, string name,
                [In, Out, MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.IUnknown)] object[] ids,
                ref uint flags, ref uint size);
    

    And the call the function like this with respect to the IUnknown pointer array -

            uint id = 5;
            uint aSize = 16;
            uint flags = 42;
            object[] aObjects = new object[aSize];
    
            uint ret = MyCPlusPlusFunction(null, id, "test", aObjects, ref flags, ref aSize);
    
    0 comments No comments

5 additional answers

Sort by: Most helpful
  1. bioan 41 Reputation points
    2021-10-01T13:06:04.117+00:00

    Hello everybody!
    Both responses are valid, the last one is better suited for my particular case !
    Thank you very much for your help without it, I can not resolve my problem!

    0 comments No comments