【发布时间】:2010-11-16 16:36:32
【问题描述】:
我正在尝试从我的 C# 应用程序中调用用 C 编写的 DLL 中的方法。以下是我实现调用的方式:
--> C方法签名:(来自第三方公司)
Int16 SSEXPORT SS_Initialize(Uint16 ServerIds[], Uint16 ServerQty, const char PTR *Binding, const char PTR *LogPath, Uint16 LogDays, Int16 LogLevel, Uint16 MaxThreads, Uint16 ThreadTTL, Int16 (CALLBACK *ProcessMessage)(Uint16, const char PTR *, Uint32, char PTR **, Uint32 PTR *, Int16 PTR *));
--> C 类型定义:
#ifndef _CSISERVERTYPES_ #define _CSISERVERTYPES_ #如果定义(OS_NT) #define CALLBACK __stdcall #define SSEXPORT __stdcall #define PTR typedef char Int8; typedef 无符号字符 Uint8; typedef 短 Int16; typedef 无符号短 Uint16; typedef long Int32; typedef unsigned long Uint32; typedef unsigned char 字节; typedef 无符号短字; typedef unsigned long Dword; typedef 短布尔值; #万一 typedef Int16 (CALLBACK *PM_Function) (Uint16,const char PTR *,Uint32,char PTR **,Uint32 PTR *,Int16 PTR *); #define SS_OK 0 #define SS_NOT_INIT -1 #define SS_PROC_ERR -2 #define SS_ERR_TCP_SRV -3 #define SS_ERR_OUT_MEM -4 #ifndef 空 #define NULL 0 #万一 #万一--> C# DLL 方法声明:
[DllImport("CSITCPServer.dll", SetLastError = true)]
static extern Int16 SS_Initialize(
UInt16[] ServerIds,
UInt16 ServerQty,
ref string Binding,
ref string LogPath,
UInt16 LogDays,
Int16 LogLevel,
UInt16 MaxThreads,
UInt16 ThreadTTL,
ProcessMessageCallback callback);
方法调用:
public static void Call_SS_Initialize()
{
Int16 ret;
UInt16[] serverIds = new UInt16[] { 2020, 2021 };
string binding = "";
string logPath = "";
try
{
ret = SS_Initialize(
serverIds,
Convert.ToUInt16(serverIds.ToList().Count),
ref binding,
ref logPath,
10,
0,
256,
300,
ProcessMessage);
Console.WriteLine("Call_SS_Initialize() -> Result of SS_Initialize: {0}", ret.ToString());
}
catch (Exception ex)
{
Int32 err = Marshal.GetLastWin32Error();
throw new Win32Exception(err);
//throw;
}
}
然后我得到 Win32Exception: 1008 - 尝试引用不存在的令牌
我知道问题一定出在非托管 (C) 和托管 (C#) 代码之间的 CHAR 到 STRING 转换中。如果我修改 Binding 或 LogPath 参数以键入 SByte,它不会给出任何错误。但由于该方法需要一个文本(字符串),我不知道如何将文本传递给该方法,因为它需要一个 SByte 变量...
我知道我可能必须使用 MarshalAs 之类的东西,但我尝试了几个选项,但都没有成功。
谁能告诉我我做错了什么??
非常感谢!!
这里是回调定义:
public delegate Int16 ProcessMessageCallback(
UInt16 ServerId,
[MarshalAs(UnmanagedType.LPStr)] ref string RequestMsg,
UInt32 RequestSize,
[MarshalAs(UnmanagedType.LPStr)] ref string ResponseMsg,
ref UInt32 ResponseSize,
ref Int16 AppErrCode);
问题是 C DLL 方法需要一个“REF”参数。对 SS_Initialize 的调用将执行附加到 ProcessMessage 回调函数。在这个函数中,我需要能够从 SS_Initialize 获取修改后的参数(参考)...
您能否建议您认为代码的结构应该如何?
谢谢!!
【问题讨论】: