V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
justou
V2EX  ›  程序员

C#传参 C++(怕是又遇到编码问题)

  •  
  •   justou · 2017-10-09 10:32:12 +08:00 · 1885 次点击
    这是一个创建于 2381 天前的主题,其中的信息可能已经有所发展或是发生改变。
    一个 c++函数接收一个 const char* names[]参数, c#那边调用这个函数如何传参的问题.

    如果仅仅是 ascii 字符串, 像传递这样的参数没问题, string[] abc = { "contents", "title" };

    但是传递 string[] abc = { "正文", "标题" }就有问题了, 字符串传递不全, 如何解决?

    这儿有个 vs2013 工程可供测试:
    链接: http://pan.baidu.com/s/1gfrMbtx 密码:yskx
    7 条回复    2017-10-09 15:58:23 +08:00
    Magentaize
        1
    Magentaize  
       2017-10-09 12:26:38 +08:00
    MessageBoxW
    Magentaize
        2
    Magentaize  
       2017-10-09 12:39:30 +08:00
    但是使用 utf8 无疑是更加合理的做法
    justou
        3
    justou  
    OP
       2017-10-09 12:42:34 +08:00
    @peoleser 试了下, 不得行呢. MessageBox 在这儿也许不太合适, 可以把函数改为:

    void stringtest(int nCount, const char* stringArray[])
    {
    ofstream of;
    of.open("test.txt");
    of << stringArray[0] << ", " << stringArray[1] << endl;

    of << "正文, 标题" << endl;
    }


    只要把正确的字节传递过来就好了, 不管它具体什么编码, 这里就是没接收到完整的字节
    justou
        4
    justou  
    OP
       2017-10-09 12:45:52 +08:00
    c#那边也这样试过:
    extern static void stringtest(int nCount, byte[][] stringArray);

    byte[][] abc = { Encoding.UTF8.GetBytes("正文"), Encoding.UTF8.GetBytes("标题") };

    但是有运行时错误, 嵌套的数组不支持封送处理.
    Magentaize
        5
    Magentaize  
       2017-10-09 13:11:22 +08:00 via Android
    你的代码里用的是 MessageBoxA,该函数只能处理短字符( ANSI ),换成 MessageBoxW 同时把函数签名里的 char*换为 LPCWSTR
    hjc4869
        6
    hjc4869  
       2017-10-09 13:17:14 +08:00 via Android   ❤️ 1
    C++那边换成 wchar_t,然后 C#这边把 dllimport 的 charset 设置成 unicode
    justou
        7
    justou  
    OP
       2017-10-09 15:58:23 +08:00
    @peoleser
    @hjc4869 可行, 就是这个 charset 设置问题
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5290 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 09:39 · PVG 17:39 · LAX 02:39 · JFK 05:39
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.