3

I've a DLL written in C++. A function of this DLL is like the following code:

C++ code:

     char _H *GetPalette() {

            -------Functions body

            -------Functions body

            return pPaletteString;

      }

Now I want to get the Pallet String from that GetPalette() function in C# code.

How could I get string from that function? I've tried this in C# code. But could not get the correct result.

C# code:

    [DllImport("cl.dll", EntryPoint = "GetPalette@0", CallingConvention = CallingConvention.StdCall)]

    private static extern IntPtr libGetPalette();

    public IntPtr GetPalette()
    {
        return libGetPalette();
    }

Finally I want to get string like this

            IntPtr result;
            result = imgProcess.GetPallet();

            string pallet;
            pallet = Marshal.PtrToStringAnsi(result);
            MessageBox.Show(pallet);

This code does not work properly. Can some body plz help me, How could I get the string value from my C++ DLL function?

Thanks

Shahriar

Shahriar Hasan Sayeed
  • 5,387
  • 1
  • 16
  • 12

2 Answers2

1

You've told C# that the calling convention is __stdcall but there's no evidence of __stdcall marking on the function itself. In addition, char* could be UTF-8.

Puppy
  • 144,682
  • 38
  • 256
  • 465
  • Actually, I'm new in .net Interoperability/Marshalling . I've used this stdcall convention code from other sources. May be I'm wrong. So what can I do now to get string from that C++ DLL function? Thanks – Shahriar Hasan Sayeed May 02 '11 at 10:36
  • 1
    Changing your C# code to match the calling convention of the C++ code would be a start. – Security Hound May 02 '11 at 12:03
1

You can define your C++ function in C# code with string return type.

[DllImport("cl.dll")]
private static extern string GetPalette();

And than simply call it from in your C# code.

string palette = GetPalette();

Within DllImport attribute you might need to set correct calling convention CallingConvention and character encoding CharSet

Lukas Kabrt
  • 5,441
  • 4
  • 43
  • 58
  • I think you might want to explain the onwership semantics of the returned buffers (IIRC .NET will free the memory with free()?) – sehe May 02 '11 at 17:12
  • Thanks Lukas Kabrt. Your answer is 100% correct. I've used CharSet=CharSet.Ansi and changed my functions return type as string. And now I'm getting the correct results. – Shahriar Hasan Sayeed May 03 '11 at 05:01