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

2
  • 2
    It is good practice to define what error or behavior you are getting. How can we know what does "This code does not work properly" mean? Commented May 2, 2011 at 10:17
  • I've got '-->' characters from that code. But it should return as like '473757.473767.574767.............' string. Commented May 2, 2011 at 10:28

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

2 Comments

I think you might want to explain the onwership semantics of the returned buffers (IIRC .NET will free the memory with free()?)
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.
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.

2 Comments

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
Changing your C# code to match the calling convention of the C++ code would be a start.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.