我从 c# 调用非托管 VB COM dll 时遇到问题。这是使用 loadLibrary 和 GetProcAddress 的动态调用。
我可以使用 loadLibrary 成功加载 dll,但 GetProcAddress 始终返回 0。它没有记录任何错误消息,什么也没有。它只返回 0。
在示例代码下方
VB COM
VERSION 1.0 CLASS
BEGIN
MultiUse = -1
Persistable = 0
DataBindingBehavior = 0
DataSourceBehavior = 0
MTSTransactionMode = 0
END
Attribute VB_Name = "Sample"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = True
Attribute VB_PredeclaredId = False
Attribute VB_Exposed = True
Option Explicit
Private Attribute1 As String
Private Sub Class_Initialize()
Attribute1 = "test"
End Sub
Public Sub TestSub()
End Sub
Public Function testFunction() As String
testFunction = "default.html"
End Function
Public Function SetData(XML As String) As String
SetData = Date + Time
End Function
c# 代码
static class UnManagedInvoker
{
[DllImport("kernel32.dll")]
private static extern IntPtr LoadLibrary([MarshalAs(UnmanagedType.LPStr)] string dllToLoad);
[DllImport("kernel32.dll")]
private static extern IntPtr GetProcAddress(IntPtr hModule, [MarshalAs(UnmanagedType.LPStr)] string procedureName);
[DllImport("kernel32.dll")]
private static extern bool FreeLibrary(IntPtr hModule);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate string MethodToInvoke(string sdata);
public static string InvokeUnmanagedDll(string dllPath, string methodName)
{
IntPtr DIedDll = LoadLibrary(dllPath);
IntPtr AddressOfFunction = GetProcAddress(DIedDll, methodName);
MethodToInvoke MI = (MethodToInvoke)Marshal.GetDelegateForFunctionPointer(AddressOfFunction, typeof(MethodToInvoke));
string data = MI("ssdasda");
FreeLibrary(DIedDll);
return data;
}
}
和调用代码
string res = UnManagedInvoker.InvokeUnmanagedDll("xx.dll","SetData");
有人可以帮我吗..
更新:
如果组件已注册,我可以成功调用方法。使用下面的代码
Type Med = Type.GetTypeFromCLSID(new Guid("089DD8B0-E12B-439B-B52C-007CA72C93D0"));
object MedObj = Activator.CreateInstance(Med);
object[] parameter = new object[1];
parameter[0] = "asdasd";
var ss = Med.InvokeMember("SetData", System.Reflection.BindingFlags.InvokeMethod, null, MedObj, parameter);
如果 dll 没有注册,有什么办法吗?