2011-11-16 19 views
0

我需要創建一個C++ dll,它將通過stdcall從另一個程序中調用。通過stdcall操作字符串到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 

,這裏是我使用來測試一個簡單的C#程序我的測試DLL:

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)如果我取消在dll文件中用//////註釋的行註釋,程序崩潰。爲什麼?

3)很顯然,我想要做的DLL中的更多的東西(的部分中/ * * /),比它做什麼的權利,但我第一2個問題受阻......

感謝所有的幫助

回答

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; 
    } 
+0

感謝,以及我從另一個工作程序,模式...我不明白爲什麼它不應該與我的測試工作,但什麼你會建議使用嗎? – ibiza

+0

事實上,真正的調用者不會是C#程序,而是MQL4程序...請參閱http://forum.mql4.com/35537,這是我獲得當前實現將字符串傳遞給C++ dll一個結構,它是根據其他人的工作 – ibiza

+0

我不確定MQL4是..但對於C#我給你正確的答案 –