简体   繁体   English

从C#到C-DLL调用/封送该结构时,为什么此字符串为空?

[英]Why is this String empty when invoking/marshaling this struct from C# to C-DLL?

I got a function like this defined in a C-DLL: 我在C-DLL中定义了这样的功能:

int AcquireArchive (char* archiveName, Password* password)

The struct Password is defined in the DLL as: DLL中将struct密码定义为:

typedef struct password {
unsigned char* pPwd;
unsigned long length;
} Password;

What I am doing is trying to wrap this function in C# using: 我正在做的是尝试使用以下方法在C#中包装此函数:

[DllImport("name.dll", CharSet = CharSet.Ansi, EntryPoint = "_AcquireArchive@16", 
CallingConvention = CallingConvention.StdCall)]
public static extern int AcquireArchive(
[MarshalAs(UnmanagedType.LPStr)] string archiveName, 
ref Password password
);

and: 和:

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct Password
{ 
    public string pwd;
    public ulong length;
}

I call this function by: 我通过以下方式调用此函数:

Password password;
password.pwd = "password";
password.length = (ulong)password.pwd.Length;

int code = AcquireArchive("Archive", ref password);

Now the problem is that the returned code signals INVALID PASSWORD, indicating (according to the documentation) a password-length of 0. Is it possible the value of password.pwd and/or password.length get lost in the invocation/marshalling process? 现在的问题是,返回的代码将发出INVALID PASSWORD信号,表示(根据文档)密码长度为0。是否有可能在调用/编组过程中丢失password.pwd和/或password.length的值?

Sadly I don't have access to the source-code of the dll. 可悲的是,我无权访问dll的源代码。

EDIT: CharSet is now Ansi, TYPO "length", removed [UnmanagedType.BStr] 编辑:CharSet现在是Ansi,TYPO“长度”,已删除[UnmanagedType.BStr]

at least one problem I see: 我至少看到一个问题:
in your C Code (length is 32 or 64 bit depending to the DLL): 在您的C代码中(长度为32或64位,具体取决于DLL):

typedef struct {
  unsigned char* pPwd;
  unsigned long length;
} Password;

and in your C# code(length is 64 bit): 并在您的C#代码中(长度为64位):

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct Password
{ 
    public string pwd;
    public ulong length;
}

if it is 64 bit , it is OK. 如果是64位,则可以。 but if it is 32 bit, you should change your C# ulong to uint like this: 但如果是32位,则应将C# ulong更改为uint如下所示:

public struct Password
{
    public string pwd;
    public uint length;
}  

I hope this helps. 我希望这有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM