【发布时间】:2013-06-28 06:33:15
【问题描述】:
我有一个带有类 LoginClass 和函数 LoginUser 的 vb6 COM dll。我需要从 C# 动态调用这个 vb6 COM dll。我正在尝试在 C# 代码下面动态访问它,但即使在 LoadLibrary 返回指针之后,GetProcAddress 也返回 0。
static class NativeMethods
{
[DllImport("kernel32", SetLastError = true, CharSet = CharSet.Unicode)]
public static extern IntPtr LoadLibrary(string dllToLoad);
[DllImport("kernel32", CharSet = CharSet.Ansi, ExactSpelling = true, SetLastError = true)]
public static extern IntPtr GetProcAddress(IntPtr hModule, string procedureName);
[DllImport("kernel32")]
public static extern bool FreeLibrary(IntPtr hModule);
}
class COMCommands
{
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate string Login(string userName, string Password, bool Result);
public string CallLoginCommand(string UserName, string Password, ref bool Result)
{
IntPtr pDll = NativeMethods.LoadLibrary(@"D:\MyCOMdll.dll");
IntPtr pAddressOfFunctionToCall = NativeMethods.GetProcAddress(pDll, "LoginUser");
Login CallLogin = (Login)Marshal.GetDelegateForFunctionPointer(pAddressOfFunctionToCall, typeof(Login));
string theResult = CallLogin(UserName, Password, Result);
bool result = NativeMethods.FreeLibrary(pDll);
return theResult;
}
}
【问题讨论】:
-
你不能这样调用VB6库,它不会导出任何你可以导入的“C风格”函数。看看this link。
-
这是否意味着无法从 C# 动态调用 vb6 COM dll。
-
不,你总是可以通过COM互操作调用它们,你只是不能DllImport(它或多或少相当于LoadLibrary + GetProcAddress)一个导出函数(其实是因为没有C风格的导出函数)。
标签: c# com vb6 marshalling com-interop