Shahriar Hasan Sayeed
Shahriar Hasan Sayeed

Reputation: 5935

C# get string/characters value from c++ function which return char pointer

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

Upvotes: 3

Views: 2510

Answers (2)

Lukas Kabrt
Lukas Kabrt

Reputation: 5489

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

Upvotes: 1

Puppy
Puppy

Reputation: 146910

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.

Upvotes: 1

Related Questions