简体   繁体   English

将char *缓冲区作为StringBuilder传递给C#

[英]Passing char* buffer to C# as a StringBuilder

I have a C++ function that is called with a char* buffer to be used for the output. 我有一个C ++函数,该函数用char *缓冲区调用以用于输出。 Now i want to write to it using C# so i need to call a managed method from the C++ function. 现在,我想使用C#对其进行写入,因此我需要从C ++函数调用托管方法。 What i can't figure out is how to pass it as a StringBuilder. 我不知道的是如何将其作为StringBuilder传递。

I previously used Robert Giesecke's Unmanaged Exports which worked fine and did this automatically using a default string marshalling scheme, but i want to use the size parameter for the MaxCapacity of the StringBuilder. 我以前使用过Robert Giesecke的“非托管导出” ,它运作良好,并使用默认的字符串编组方案自动完成了此操作,但我想将size参数用于StringBuilder的MaxCapacity。

Is there a nicer way to do this than creating a new StringBuilder instance, writing to it, getting a CLR string with ToString() , and then copying the contents to the buffer? 有没有比创建新的StringBuilder实例,对其进行写入,使用ToString()获取CLR字符串,然后将内容复制到缓冲区更好的方法呢? The strings in question might be as long as 10,000 characters and i don't really like the idea of copying it twice each time. 有问题的字符串可能长达10,000个字符,我真的不喜欢每次复制两次的想法。

C# C#

public static void MyMethod(StringBuilder buffer)
{
    //...
}

C++/CLI C ++ / CLI

extern "C" __declspec(dllexport)
void __stdcall MyFunction(char* buffer, int length)
{
    MyNamespace::MyClass::MyMethod( /* ? */ );
}
  1. Use a byte [] then c++ 8 bit character array will align correctly. 使用byte []则c ++ 8位字符数组将正确对齐。

  2. I prefer to do something similar to this because I use it for unmanaged code: 我喜欢做与此类似的事情,因为我将其用于非托管代码:

     String ^ ToManagedString(const char * pString) { return Marshal::PtrToStringAnsi(IntPtr((char *)pString)); // Marshal pString into Managed Memory. return as a C# string reference (^). } const std::string ToStdString(String ^ strString) { IntPtr ptrString = IntPtr::Zero; std::string strStdString; try { ptrString = Marshal::StringToHGlobalAnsi(strString); // Marshal a C# String reference into unmanaged HEAP memory space. strStdString = (char *)ptrString.ToPointer(); // Convert C# IntPtr to char* implicitly, call assignment operator of std::string to copy. } finally { if (ptrString != IntPtr::Zero) { Marshal::FreeHGlobal(ptrString); } } return strStdString; // return std::string copied out of interop unmanaged heap space } 

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

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