当 invoking/marshaling 这个结构从 C# 到 C-DLL 时,为什么这个字符串是空的?
Why is this String empty when invoking/marshaling this struct from C# to C-DLL?
我在 C-DLL 中定义了这样一个函数:
int AcquireArchive (char* archiveName, Password* password)
结构密码在 DLL 中定义为:
typedef struct password {
unsigned char* pPwd;
unsigned long length;
} Password;
我正在做的是尝试使用 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
);
和:
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct Password
{
public string pwd;
public ulong length;
}
我通过以下方式调用此函数:
Password password;
password.pwd = "password";
password.length = (ulong)password.pwd.Length;
int code = AcquireArchive("Archive", ref password);
现在的问题是返回的代码发出 INVALID PASSWORD 信号,表明(根据文档)密码长度为 0。
password.pwd and/or password.length 的值是否可能在 invocation/marshalling 过程中丢失?
遗憾的是我无法访问 dll 的源代码。
编辑:CharSet 现在是 Ansi,错字 "length",已删除 [UnmanagedType.BStr]
我至少看到一个问题:
在您的 C 代码中(长度为 32 位或 64 位,具体取决于 DLL):
typedef struct {
unsigned char* pPwd;
unsigned long length;
} Password;
在您的 C# 代码中(长度为 64 位):
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct Password
{
public string pwd;
public ulong length;
}
如果是64位就可以了。
但是如果它是 32 位的,你应该改变你的 C# ulong
到 uint
像这样:
public struct Password
{
public string pwd;
public uint length;
}
希望对您有所帮助。
我在 C-DLL 中定义了这样一个函数:
int AcquireArchive (char* archiveName, Password* password)
结构密码在 DLL 中定义为:
typedef struct password {
unsigned char* pPwd;
unsigned long length;
} Password;
我正在做的是尝试使用 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
);
和:
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct Password
{
public string pwd;
public ulong length;
}
我通过以下方式调用此函数:
Password password;
password.pwd = "password";
password.length = (ulong)password.pwd.Length;
int code = AcquireArchive("Archive", ref password);
现在的问题是返回的代码发出 INVALID PASSWORD 信号,表明(根据文档)密码长度为 0。 password.pwd and/or password.length 的值是否可能在 invocation/marshalling 过程中丢失?
遗憾的是我无法访问 dll 的源代码。
编辑:CharSet 现在是 Ansi,错字 "length",已删除 [UnmanagedType.BStr]
我至少看到一个问题:
在您的 C 代码中(长度为 32 位或 64 位,具体取决于 DLL):
typedef struct {
unsigned char* pPwd;
unsigned long length;
} Password;
在您的 C# 代码中(长度为 64 位):
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct Password
{
public string pwd;
public ulong length;
}
如果是64位就可以了。
但是如果它是 32 位的,你应该改变你的 C# ulong
到 uint
像这样:
public struct Password
{
public string pwd;
public uint length;
}
希望对您有所帮助。