本文介绍了C#GetProcAddress的返回零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

出于某种原因,每当我的C#.NET 2.0的应用程序进行调用以 GetProcAddress的它总是返回为零。

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.
    }
}



我敢肯定,函数名称拼写是否正确,和 _fullPath 大概是正确的,因为 _dllHandle 总是被分配了一个非零值。您可以提供任何见解表示赞赏。谢谢你。

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的只配备在ANSI的味道,因此我们告诉它帮助运行时编组时请始终使用ANSI字符串参数。我们还防止运行时寻找一个不存在的GetProcAddressA,因为对于C#的默认是设置ExactSpelling到假

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.

这篇关于C#GetProcAddress的返回零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-12 10:27