文字列

概要

文字列のやりとり

文字列

C++へと渡すだけの場合は、C#のString、C++で文字列を書き換える場合、C#のStringBuilderとなります。 C++にてchar受け取りならCharSet=CharSet.Ansi、C++にてwchar_t受けとりならCharSet = CharSet.Unicode を使います。

  • C++側のソース

    Dll1.dllとしてコンパイル
    #include <windows.h>
    #include <cstddef>
    #include <iostream>
    #include <stdio.h>
    #include <string.h>
    
    using namespace std;
    
    #define DLLEXPORT __declspec(dllexport) WINAPI
    
    
    
    // char文字列を受け取るのみ
    extern "C" void DLLEXPORT dllSendString(const char *pszString) {
    	MessageBoxA(NULL, pszString, pszString, NULL);
    }
    
    // wchar_t文字列を受け取るのみ
    extern "C" void DLLEXPORT dllSendWString(const wchar_t* pwszString) {
    	MessageBoxW(NULL, pwszString, pwszString, NULL);
    }
    
    // char文字列を受け取り、上書きする (書き換えの上限はC#側のStringBuilderのサイズまで)
    extern "C" void DLLEXPORT dllSendAndRecieveString(char* pszString) {
    	wcout << pszString << endl;
    	const char* newPszString = "新しい文字列は①";
    	strcpy_s(pszString, 255, newPszString);
    }
    
    // wchar_t文字列を受け取り、上書きする (書き換えの上限はC#側のStringBuilderのサイズまで)
    extern "C" void DLLEXPORT dllSendAndRecieveWString(wchar_t* pwszString) {
    	wcout << pwszString << endl;
    	const wchar_t* newPszString = L"新しい文字列は②";
    	wcscpy_s(pwszString, 255, newPszString);
    }
    
  • C#側のソース

    test1.cs
    using System;
    using System.Runtime.InteropServices;
    using System.Text;
    
    namespace test1
    {
        internal class Program
        {
            [DllImport("Dll1.dll", CharSet=CharSet.Ansi)]
            static extern void dllSendString(String sz);
    
            [DllImport("Dll1.dll", CharSet = CharSet.Unicode)]
            static extern void dllSendWString(String wsz);
    
    
            [DllImport("Dll1.dll", CharSet = CharSet.Ansi)]
            static extern void dllSendAndRecieveString(StringBuilder sz);
    
    
            [DllImport("Dll1.dll", CharSet = CharSet.Unicode)]
            static extern void dllSendAndRecieveWString(StringBuilder sz);
    
    
            static void Main(string[] args)
            {
                dllSendString("あいうえお");
                dllSendWString("かきくけこ");
    
                StringBuilder sb_ansi = new StringBuilder(255);
                dllSendAndRecieveString(sb_ansi);
                Console.WriteLine(sb_ansi.ToString());
    
                StringBuilder sb_unicode = new StringBuilder(255);
                dllSendAndRecieveWString(sb_unicode);
                Console.WriteLine(sb_unicode.ToString());
    
                Console.ReadKey();
            }
        }
    }