简体   繁体   English

C#中的std :: string?

[英]std::string in C#?

I thought the problem is inside my C++ function,but I tried this 我以为问题出在我的C ++函数内部,但是我尝试了

C++ Function in C++ dll: C ++ dll中的C ++函数:

bool __declspec( dllexport ) OpenA(std::string file)
{
return true;
}

C# code: C#代码:

[DllImport("pk2.dll")]
public static extern bool OpenA(string path);

    if (OpenA(@"E:\asdasd\"))

I get an exception that the memory is corrupt,why? 我发现内存损坏了,为什么?

If I remove the std::string parameter,it works great,but with std::string it doesnt work. 如果我删除了std :: string参数,则效果很好,但使用std :: string则不起作用。

std::string and c# string are not compatible with each other. std :: string和c#字符串彼此不兼容。 As far as I know the c# string corresponds to passing char* or wchar_t* in c++ as far as interop is concerned. 据我所知,就互操作而言,c#字符串对应于在c ++中传递char*wchar_t*
One of the reasons for this is that There can be many different implementations to std::string and c# can't assume that you're using any particular one. 原因之一是std :: string可以有许多不同的实现,而c#不能假设您使用的是任何特定的实现。

Try something like this: 尝试这样的事情:

bool __declspec( dllexport ) OpenA(const TCHAR* pFile)
{ 
   std::string filename(pFile);
   ...
   return true;
}

You should also specify the appropriate character set (unicode/ansi) in your DllImport attribute. 您还应该在DllImport属性中指定适当的字符集(unicode / ansi)。

As an aside, unrelated to your marshalling problem, one would normally pass a std:string as a const reference: const std:string& filename. 顺便说一句,与您的编组问题无关,通常会传递一个std:string作为const引用:const std:string&filename。

It's not possible to marshal a C++ std::string in the way you are attempting. 以您尝试的方式封送C ++ std :: string是不可能的。 What you really need to do here is write a wrapper function which uses a plain old const char* and converts to a std::string under the hood. 您在这里真正需要做的是编写一个包装函数,该函数使用一个普通的旧const char*并在后台转换为std :: string。

C++ C ++

extern C { 
  void OpenWrapper(const WCHAR* pName) {
    std::string name = pName;
    OpenA(name);
  }
}

C# C#

[DllImport("pk2.dll")]
public static extern void OpenWrapper( [In] string name);

I know this topic is a tad old but for future googlers, this should also work (without using char* in C++) 我知道这个主题有点陈旧,但对于将来的Google员工来说,这也应该有效(在C ++中不使用char *)

C#: C#:

public static extern bool OpenA([In, MarshalAs(UnmanagedType.LPStr)] path);

C++: C ++:

bool __declspec( dllexport ) OpenA(std::string file);

std::wstring and System.string can be compatible through below conversion: std :: wstring和System.string可以通过以下转换兼容:

C++ : C ++:

bool func(std::wstring str, int number)
{
  BSTR tmp_str = SysAllocStringLen(str.c_str(), str.size());
  VARIANT_BOOL ret = VARIANT_FALSE;

  // call c# COM DLL
  ptr->my_com_function(tmp_str, number, &ret);

  SysFreeString(tmp_str);

  return (ret != VARIANT_FALSE) ? true : false;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM