0

stdcallを介して別のプログラムから呼び出されるC++dllを作成する必要があります。

必要なもの:呼び出し元プログラムは文字列の配列をdllに渡し、dllは配列内の文字列値を変更する必要があります。呼び出し元プログラムは、dllから取得したこれらの文字列値を引き続き処理します。

私は簡単なテストプロジェクトを作成しましたが、明らかに何かが欠けています...

これが私のテストC++dllです:

#ifndef _DLL_H_
#define _DLL_H_

#include <string>
#include <iostream>

struct strStruct
{
    int len;
    char* string;
};

__declspec (dllexport) int __stdcall TestFunction(strStruct* s)
{
   std::cout << "Just got in dll" << std::endl;

   std::cout << s[0].string << std::endl;
   //////std::cout << s[1].string << std::endl;

   /*
   char str1[] = "foo";
   strcpy(s[0].string, str1);
   s[0].len = 3;

   char str2[] = "foobar";
   strcpy(s[1].string, str2);
   s[1].len = 6;
   */

   //std::cout << s[0].string << std::endl;
   //std::cout << s[1].string << std::endl;

   std::cout << "Getting out of dll" << std::endl;

   return 1;
}

#endif

これが、テストdllのテストに使用している単純なC#プログラムです。

 using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Text;
 using System.Runtime.InteropServices;

 namespace TestStr
 {
     class Program
     {
         [DllImport("TestStrLib.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
         public static extern int TestFunction(string[] s);

         static void Main(string[] args)
         {
             string[] test = new string[2] { "a1a1a1a1a1", "b2b2b2b2b2" };

             Console.WriteLine(test[0]);
             Console.WriteLine(test[1]);

             TestFunction(test);

             Console.WriteLine(test[0]);
             Console.WriteLine(test[1]);

             Console.ReadLine();
         }
     }
 }

そして、ここに生成された出力があります:

a1a1a1a1a1
b2b2b2b2b2
Just got in dll
b2b2b2b2b2
Getting out of dll
a1a1a1a1a1
b2b2b2b2b2

いくつか質問があります:

1)要素を最初の位置ではなく配列の2番目の位置に出力するのはなぜですか?

2)dllファイルで//////でコメントされた行のコメントを外すと、プログラムがクラッシュします。なんで?

3)明らかに、dll(/ * * /内の部分)で現在よりも多くのことを実行したかったのですが、最初の2つの質問によってブロックされています...

ご協力ありがとうございます

4

1 に答える 1

1

string[]をネイティブ構造体としてマーシャリングすることはできません

    [DllImport("TestStrLib.dll", CharSet = CharSet.Ansi, 
             CallingConvention = CallingConvention.StdCall)]
             public static extern int TestFunction(string[] s);

      struct strStruct
        {
            int len;
            char* string;
        }

    __declspec (dllexport) int __stdcall TestFunction(strStruct* s);

さまざまなタイプのマーシャリングについては、http://msdn.microsoft.com/en-us/library/fzhhdwae.aspxを読みください。

C#では

    [DllImport( "TestStrLib.dll" )]
    public static extern int TestFunction([In, Out] string[] stringArray
    , int size);

C++では

__declspec(dllexport) int TestFunction( char* ppStrArray[], int size)
   {
       return 0;
   }
于 2011-11-16T01:40:59.673 に答える