IT博客汇
  • 首页
  • 精华
  • 技术
  • 设计
  • 资讯
  • 扯淡
  • 权利声明
  • 登录 注册

    如何:使用 C++ Interop 封送 Unicode 字符串

    天下发表于 2015-12-01 03:09:00
    love 0
    // MarshalUnicode1.cpp
    // compile with: /clr
    #include <iostream>
    #include <stdio.h>
    #include <vcclr.h>

    using namespace std;

    using namespace System;
    using namespace System::Runtime::InteropServices;

    #pragma unmanaged

    void NativeTakesAString(const wchar_t* p) {
       printf_s("(native) recieved '%S'\n", p);
    }

    #pragma managed
     
    int main() {
       String^ s = gcnew String("test string");
       pin_ptr<const wchar_t> str = PtrToStringChars(s);

       Console::WriteLine("(managed) passing string to native func");
       NativeTakesAString( str );
    }
     

    下面的示例演示在非托管函数调用的托管函数中访问 Unicode 字符串时需要的数据封送处理。一旦托管函数接收到本机 Unicode 字符串,就会使用 PtrToStringUni 方法将其转换为托管字符串。

      复制代码 
    // MarshalUnicode2.cpp
    // compile with: /clr
    #include <iostream>

    using namespace std;
    using namespace System;
    using namespace System::Runtime::InteropServices;

    #pragma managed

    void ManagedStringFunc(wchar_t* s) {
       String^ ms = Marshal::PtrToStringUni((IntPtr)s);
       Console::WriteLine("(managed) recieved '{0}'", ms);
    }

    #pragma unmanaged

    void NativeProvidesAString() {
       cout << "(unmanaged) calling managed func\n";
       ManagedStringFunc(L"test string");
    }

    #pragma managed

    int main() {
       NativeProvidesAString();
    }
     


    天下 2015-12-01 11:09 发表评论


沪ICP备19023445号-2号
友情链接