问题描述
由于某种原因,每当我的C#.NET 2.0应用程序调用 GetProcAddress
,它始终返回零。 public class MyClass
{
内部静态类UnsafeNativeMethods
{
[DllImport(kernel32.dll,CharSet = CharSet.Auto ,SetLastError = true)]
内部静态extern IntPtr LoadLibrary(string lpFileName);
[DllImport(kernel32.dll,CharSet = CharSet.Auto,SetLastError = true)]
内部静态extern bool SetDllDirectory(string lpPathName);
[DllImport(kernel32.dll,CharSet = CharSet.Auto,SetLastError = true)]
内部静态extern IntPtr GetProcAddress(IntPtr hModule,string procName);
}
private void MyFunc()
{
IntPtr _dllHandle;
IntPtr _fptr;
string _fullPath =.\\mydll.dll;
string _procName =MyDllFunc;
_dllHandle = UnsafeNativeMethods.LoadLibrary(_fullPath);
_fptr = UnsafeNativeMethods.GetProcAddress(_dllHandle,_procName); //< - 始终返回零。
}
}
我确定功能名称拼写正确,而 _fullPath
可能是正确的,因为 _dllHandle
总是被赋值为非零值。您可能能够提供的任何见解表示赞赏。谢谢。
GetProcAddress只有ANSI风格,因此我们通过告诉它在编组字符串参数。我们还阻止运行时查找不存在的GetProcAddressA,因为C#的默认值是将ExactSpelling设置为false。
For some reason, whenever my C# .NET 2.0 application makes a call to GetProcAddress
it always returns zero.
public class MyClass
{
internal static class UnsafeNativeMethods
{
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
internal static extern IntPtr LoadLibrary(string lpFileName);
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
internal static extern bool SetDllDirectory(string lpPathName);
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
internal static extern IntPtr GetProcAddress(IntPtr hModule, string procName);
}
private void MyFunc()
{
IntPtr _dllHandle;
IntPtr _fptr;
string _fullPath = ".\\mydll.dll";
string _procName = "MyDllFunc";
_dllHandle = UnsafeNativeMethods.LoadLibrary(_fullPath);
_fptr = UnsafeNativeMethods.GetProcAddress(_dllHandle, _procName); // <-- Always returns zero.
}
}
I'm sure the function name is spelled correctly, and _fullPath
is presumably correct because _dllHandle
is always assigned a non-zero value. Any insight you may be able to provide is appreciated. Thanks.
GetProcAddress only comes in an ANSI flavor, hence we help the runtime by telling it to always use ANSI when marshalling the string parameter. We also prevent the runtime looking for a non-existent GetProcAddressA, because the default for C# is to set ExactSpelling to false.
http://www.pinvoke.net/default.aspx/kernel32.getprocaddress
这篇关于C#GetProcAddress返回零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!