C# 从 c++ 获取字符串/字符值返回 char 指针的函数

发布于 2024-11-04 11:42:48 字数 926 浏览 5 评论 0原文

我有一个用 C++ 编写的 DLL。该 DLL 的函数类似于以下代码:

C++ 代码:

     char _H *GetPalette() {

            -------Functions body

            -------Functions body

            return pPaletteString;

      }

现在我想从 C# 代码中的 GetPalette() 函数获取 Pallet String。

我如何从该函数中获取字符串? 我已经在 C# 代码中尝试过这个。但无法得到正确的结果。

C# 代码:

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

    private static extern IntPtr libGetPalette();

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

最后我想得到这样的字符串

            IntPtr result;
            result = imgProcess.GetPallet();

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

此代码无法正常工作。 有人可以帮我吗,我怎样才能从我的 C++ DLL 函数中获取字符串值?

谢谢沙赫里亚尔

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

后知后觉 2024-11-11 11:42:48

您可以使用字符串返回类型在 C# 代码中定义 C++ 函数。

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

而不是简单地从 C# 代码中调用它。

string palette = GetPalette();

DllImport 属性中,您可能需要设置正确的调用约定 CallingConvention 和字符编码 CharSet

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

日记撕了你也走了 2024-11-11 11:42:48

您已经告诉 C# 调用约定是 __stdcall,但没有证据表明函数本身有 __stdcall 标记。此外,char* 可以是 UTF-8。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文