-1

I'm trying to call a function in a C++ dll, from C# code.

The C++ function :

#ifdef NT2000
      __declspec(dllexport)
    #endif

    void MyFunction
            (   long            *Code,
                long            Number,
                unsigned char   *Reference,
                unsigned char   *Result         ) ;

And my C# call is :

 [DllImport("mydll.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern void MyFunction(ref IntPtr Code,
        int Number,
        string Reference,
        ref IntPtr Result);

This function is supposed to return "Code" and "Result"

The "Code" value that I get seems to be ok, but "Result" seems not ok, so I'm wondering if I'm getting the string value that I expect or the memory address ?

Thanks for your help.

  • 2
    Please show the body of `MyFunction` and please see [mre]. Also, what are you getting and what are you expecting? – Paul Sanders Jun 22 '22 at 11:18
  • How big is the `Result` buffer supposed to be? There seems no way to pass in a size – Charlieface Jun 22 '22 at 11:38
  • Are you aware that C++ and C# use totally different memory models? For interop between C++ and C# I always use C++/CLI (https://www.codeproject.com/Articles/19354/Quick-C-CLI-Learn-C-CLI-in-less-than-10-minutes). In any case you will need to ensure C# knows it is dealing with pointers it doesn't own and thus should not cleanup itself. – Pepijn Kramer Jun 22 '22 at 12:09
  • My Result is supposed to have a size = 20 – CodeFingers Jun 22 '22 at 12:52

1 Answers1

1

long in C maps to int in C#. And char is ANSI, so you need to specify UnmanagedType.LPStr. The Result appears to be an out parameter, for which you will need to pre-assign a buffer (size unknown?) and pass it as StringBuilder

[DllImport("mydll.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern void MyFunction(
        ref int Code,
        int Number,
        [MarshalAs(UnmanagedType.LPStr)]
        string Reference,
        [MarshalAs(UnmanagedType.LPStr), Out]
        StringBuilder Result);

Use it like this

var buffer = new StringBuilder(1024); // or some other size
MyFunction(ref myCode, myNumber, myReference, buffer);
Charlieface
  • 52,284
  • 6
  • 19
  • 43
  • Thanks a lot ! It's almost give me what I expect. Expected : 39656136788582617901 Result : 396561367885826179011212231543 So I think that as you said, I need to pre-assign a buffer, with a size, how to do that please ? – CodeFingers Jun 22 '22 at 12:49
  • It's working with : StringBuilder buffer = new StringBuilder("", 19); //The size that I need is 20 – CodeFingers Jun 22 '22 at 13:16
  • If I use : var buffer = new StringBuilder[1024]; buffer will be an array, so not accepted – CodeFingers Jun 22 '22 at 13:18
  • Thank you very much, my problem is solved :-) – CodeFingers Jun 22 '22 at 13:27