调用从c#到c++的外部方法
P/Invoke external method from C# to C++
我编写了以下c++共享库:
#include "iostream"
#if defined(_WIN32) || defined(_WIN64)
#define Q_DECL_EXPORT __declspec(dllexport)
#define Q_DECL_IMPORT __declspec(dllimport)
#else
#define Q_DECL_EXPORT
#define Q_DECL_IMPORT
#endif
#ifdef MATINCHESS_LIBRARY
# define MATINCHESS_API Q_DECL_EXPORT
#else
# define MATINCHESS_API Q_DECL_IMPORT
#endif
using namespace std;
string* memory;
extern "C"
{
MATINCHESS_API void Initialize();
MATINCHESS_API void Uninitialize();
MATINCHESS_API void Put(string text);
MATINCHESS_API string Get();
void Initialize()
{
memory = new string;
}
void Uninitialize()
{
delete memory;
}
void Put(string text)
{
memory->assign(text);
}
string Get()
{
return *memory;
}
}
这是我的c#控制台应用程序:
using System;
using System.Runtime.InteropServices;
namespace MatinChess
{
class MainClass
{
const string MatinChessDLL = "libMatinChessDLL.so";
[DllImport(MatinChessDLL)]
public static extern void Initialize();
[DllImport(MatinChessDLL)]
public static extern void Uninitialize();
[DllImport(MatinChessDLL)]
public static extern void Put(string text);
[DllImport(MatinChessDLL)]
public static extern string Get();
public static void Main (string[] args)
{
Console.WriteLine ("Initializing...");
Initialize ();
Console.WriteLine ("Initialized");
Console.WriteLine ("Write: ");
Put (Console.ReadLine ());
Console.WriteLine ("Value is put.");
Console.WriteLine ("You wrote "" + Get () + """);
Console.ReadKey ();
Console.WriteLine ("Uninitializing...");
Uninitialize ();
Console.WriteLine ("Uninitialized");
}
}
}
它安全地初始化并放入ReadLine
中的字符串,但是当它想调用Get
方法时,它崩溃并产生长堆栈跟踪。
请帮我找一下问题
不能将std::string
从c++封送到c#。你必须使用字符缓冲区。参见这个问题:将字符串从c#传递到c++ dll并返回——最小示例
相关文章:
- 使用 Git 处理 C++ Visual Studio 2019 解决方案的外部依赖项源代码管理的最佳方法是什么?
- 仅在少数方法(静态或共享库)中解析的外部符号
- Windows C++静态库在初始化期间无法访问外部方法
- 从类C++外部调用指向成员方法的成员指针
- const_cast const 方法中的"this"将"this"分配给外部变量?
- C 将方法和字段带入外部范围,而无需明确的参考
- 将类方法设置为外部定义的函数
- const 类方法是否阻止在类外部分配变量?
- 我可以在外部组装(function.asm)中制作C 方法吗?
- Qt的GUI线程在从外部对象调用方法时是否会在引擎盖下生成线程?
- 是否有一种方法可以让公共成员在班级外部无法解码,而无需访问包装器功能
- 电子内部或外部方法创建自己的右键单击上下文菜单 - Windows
- 直接调用外部方法时的访问违规异常
- 有没有一种很好的跨平台方法可以使用CMake包含外部C++库
- 如何在WebBrowser控件窗口中生成异常.MFC中实现的外部方法
- 卤化外部方法
- 调用从c#到c++的外部方法
- objectivec-使用Obj-c/Obj-c++中的c++对象-调用外部方法
- 使用外部方法跳出循环
- 设计模式 - C++哪里需要本地扩展或外部方法?