为什么我不能在 Release 版本中将 char* 字符串从 C++ 返回到 C#? [英] Why can't I return a char* string from C++ to C# in a Release build?

查看:29
本文介绍了为什么我不能在 Release 版本中将 char* 字符串从 C++ 返回到 C#?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从 C# 调用以下简单的 C 函数:

I'm attempting to call the following trivial C function from C#:

SIMPLEDLL_API const char* ReturnString()
{
    return "Returning a static string!";
}

使用以下 P/Invoke 声明(带或不带 return 属性,没有区别):

With the following P/Invoke declaration (with or without the return attribute, it makes no difference):

[DllImport("SimpleDll")]
[return: MarshalAs(UnmanagedType.LPStr)]
public static extern string ReturnString();

如果 DLL 是调试版本,但在发布版本中崩溃 (AccessViolationException),它可以工作.

It works if the DLL is a Debug build but crashes in a Release build (AccessViolationException).

我正在调用十几个其他简单的函数,这是唯一一个失败的(这里是其他函数:)

I am calling over a dozen other simple functions and this is the only one that fails (here are the others:)

[DllImport("SimpleDll")] public static extern int NextInt();
[DllImport("SimpleDll")] public static extern void SetNextInt(int x);
[DllImport("SimpleDll")] public static extern int AddInts(int a, int b);
[DllImport("SimpleDll")] public static extern int AddFourInts(int a, int b, int c, int d);
[DllImport("SimpleDll")] public static extern double AddDoubles(double x, double y);
[DllImport("SimpleDll")] public static extern IntPtr AddDoublesIndirect(ref double x, ref double y);
[DllImport("SimpleDll")] [return: MarshalAs(UnmanagedType.U1)]
public static extern char CharStringArgument([MarshalAs(UnmanagedType.LPStr)]string s);
[DllImport("SimpleDll")] [return: MarshalAs(UnmanagedType.U2)]
public static extern char WCharStringArgument([MarshalAs(UnmanagedType.LPWStr)]string s);
[DllImport("SimpleDll")] [return: MarshalAs(UnmanagedType.LPWStr)]
public static extern string ReturnWString();
[DllImport("SimpleDll")] [return: MarshalAs(UnmanagedType.BStr)]
public static extern string ReturnBSTR();
[DllImport("SimpleDll")] public static extern System.Drawing.Point MakePoint(int x, int y);
[DllImport("SimpleDll")] public static extern IntPtr MakePointIndirect(int x, int y);
[DllImport("SimpleDll")] public static extern int GetPointY(System.Drawing.Point p);
[DllImport("SimpleDll")] public static extern int GetPointYIndirect(ref System.Drawing.Point pp);
[DllImport("SimpleDll")] public static extern int SumIntegers(ref int firstElem, int size);

推荐答案

或者尝试使用

[DllImport("SimpleDll")]
public static extern IntPtr ReturnString();

在您的调用代码中,使用 Marshal 类

and in your calling code, use the Marshal Class

string ret = System.Runtime.InteropServices.Marshal.PtrToStringAnsi(PInvoke.ReturnString());

这篇关于为什么我不能在 Release 版本中将 char* 字符串从 C++ 返回到 C#?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆