将C#应用程序中的字符串数组传递给C ++ DLL

时间:2012-05-03 10:28:38

标签: c# c++

string []URL = {"www.facebook.com","www.orkut.com","www.yahoo.com"};
            Int32 result = URL.Length;
            SetPolicyURL( URL,result );

这是我的C#代码,我试图将字符串数组传递给C ++ Dll,这是像这样导入的

     [PreserveSig]
    [DllImport("PawCtrl.dll", SetLastError = true, CharSet = CharSet.Auto,  CallingConvention = CallingConvention.StdCall)]
    public static extern void SetPolicyURL( string []policy, Int32 noURL);

但我无法在我的c ++ DLL中收到它。

 PAWCTRL_API void __stdcall SetPolicyURL( char ** URLpolicy, __int32 noURL)
 {

for ( int i = 0; i < noURL; i++)
     {

    URLvector.push_back(URLpolicy[i]);
  }
 }

请任何人帮助我如何通过该功能

感谢InAdvance

2 个答案:

答案 0 :(得分:1)

CharSet = CharSet.Auto是错误的,它必须是CharSet.Ansi才能与本机代码中的char *兼容。如果仍有问题,请使用启用了非托管调试的调试器,在函数的第一个语句中设置断点。

同时删除[PreserveSig],这里没有任何意义。并且SetLastError很可能是错误的,这在Windows api函数中是典型的。

答案 1 :(得分:0)

将字符串数组从VB.Net传递到C的示例。与32位和64位兼容。

VB.Net:

Private Declare Function main_net32 Lib "MyCLib32.dll" Alias "_main_net@8" (ByVal argc As Int32, ByRef sArgs() As String) As Int32
Private Declare Function main_net64 Lib "MyCLib64.dll" Alias "main_net" (ByVal argc As Int32, ByRef sArgs() As String) As Int32

Private Sub MainWindow_Loaded(sender As Object, e As RoutedEventArgs) Handles Me.Loaded
    Dim sArgs() As String = Environment.GetCommandLineArgs
    Dim result As Int32
    If Environment.Is64BitProcess Then
        result = main_net64(sArgs.Length, sArgs)
    Else
        result = main_net32(sArgs.Length, sArgs)
    End If
End Sub

C:

#define DllExport(result) __declspec(dllexport) result __stdcall
DllExport(int) main_net(int argc, char ***argv)
{
    int i;
    for(i=0;i<argc;i++)
        printf("%d: %s",i,(*argv)[i]);
}