c# - 使用 DLL 在 C++ 和 C# 之间交换字符串

标签 c# c++ dll

我正在寻找将我的 C++ 代码中的字符串与我的 C# 表单进行交换。

这是我在 C# 程序中的代码:

[DllImport("libDLL.dll", CallingConvention = CallingConvention.Cdecl)]
            public static extern string valeurExpr(IntPtr pImg);

            public unsafe string objetLibValeurCarteExpr()
            {
                return valeurExpr(ClPtr);
            }

我的 C++ 程序中的代码:

IHM 类

 class IHM {
 private:
        std::string             card_number_str;
        std::string             card_expr_str;
        std::string             card_porteur_str;

我的实习生

extern "C" _declspec(dllexport) std::string valeurExpr(IHM* pImg) {     return pImg->lireExpr(); }

函数lireExpr()

 _declspec(dllexport) std::string lireExpr() const {
        return card_expr_str;
    }

当我执行 Visual 时说我尝试访问内存的 protected 部分。

最佳答案

首先,您不能在 dll 中包含 std::stringstd::wstring 以供其他语言访问。所以这些家伙必须改为 char *wchar_t * <--- 这是真正的字符串 - 字符数组。

那么,如何从 C++ 获取字符串到 C#?

C++

void foo(char *str, int len)
{
    //write here content of string
}

C#

[DllImport("...", CallingConvention = CallingConvention.Cdecl)
static extern void foo(StringBuilder str, int len);

然后你必须以某种方式调用它:

void callFoo()
{
  StringBuilder sb = new StringBuilder(10); //allocate memory for string
  foo(sb, sb.Capacity);
}

请注意,在 C# 中,您必须使用 StringBuilder 从 C++ 中获取字符串。

如果您想以其他方式传递字符串 - 从 C# 到 C++ 更简单: C++

void foo(const char *str)
{
    //do something with this str
}

C#

[DllImport("...", CallingConvention = CallingConvention.Cdecl)
static extern void foo(string str);

然后就是:

void callFoo(string str)
{
   foo(str);
}

你必须记住代码页。因此,如果您使用的是 unicode,则必须为 DllImport 提供额外的属性:CharSet=CharSet.Unicode

现在上课。没有简单的方法可以将 C++ 中定义的类传递给 C#。最简单的方法是做一些魔术。因此,对于 C++ 中的每个成员函数,创建将导出到 dll 的非成员函数。类似的东西:

//class in C++
class Foo 
{
public:
  int Bar();
};

//now you will have to define non member function to create an instance of this class:
Foo* Foo_Create() 
{ 
    return new Foo(); 
}

//and now you will have to create non member function that will call Bar() method from a object:
int Foo_Bar(Foo* pFoo) 
{ 
    return pFoo->Bar(); 
}

//in the end you will have to create a non member function to delete your object:
void Foo_Delete(Foo* pFoo) 
{ 
    delete pFoo; 
}

然后您可以在 C# 中使用它:

[DllImport("Foo.dll")]
public static extern IntPtr Foo_Create();

[DllImport("Foo.dll")]
public static extern int Foo_Bar(IntPtr value);

[DllImport("Foo.dll")]
public static extern void Foo_Delete(IntPtr value);

您也可以在 C++ 中使用 C# 类,但它有点复杂并且需要使用 C++/CLI

关于c# - 使用 DLL 在 C++ 和 C# 之间交换字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44544611/

相关文章:

c# - 忽略 MVC 包中的文件

c# - 使用 Random 和 OrderBy 是一个好的洗牌算法吗?

c++ - 如何在小部件上单击 "What' s“此”按钮时得到通知?

c# - 在 C# 应用程序中导出 C++ 函数

c# - 如何在 Visual Studio C# 2010 速成版中创建 DLL 文件?

c# - "The parameters dictionary contains a null entry for parameter"- 如何修复?

c# - 将 float 转换为 int 数将导致 int 无效

c++ - 使用 sbrk 自定义内存管理

c++ - Boost Spirit,获取语义 Action 中的迭代器

clickonce - 在单击一次的应用程序中切换 dll?