RError.com

RError.com Logo RError.com Logo

RError.com Navigation

  • 主页

Mobile menu

Close
  • 主页
  • 系统&网络
    • 热门问题
    • 最新问题
    • 标签
  • Ubuntu
    • 热门问题
    • 最新问题
    • 标签
  • 帮助
主页 / 问题 / 1082232
Accepted
HideME
HideME
Asked:2020-02-14 00:24:34 +0000 UTC2020-02-14 00:24:34 +0000 UTC 2020-02-14 00:24:34 +0000 UTC

在 .dll (c#) 中找不到函数

  • 772

在我包含的 .dll 中找不到函数(funcPtr == 0)。我假设函数的名称在内部以某种方式被编码或更改,但我自己还无法弄清楚。

程序:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace Lab1Dynamic
{
    class Program
    {
        [DllImport("kernel32", SetLastError = true, CharSet = CharSet.Ansi)]
        static extern IntPtr LoadLibrary([MarshalAs(UnmanagedType.LPStr)]string lpFileName);

        [DllImport("kernel32", CharSet = CharSet.Ansi, ExactSpelling = true, SetLastError = true)]
        static extern IntPtr GetProcAddress(IntPtr hModule, string procName);

        [DllImport("kernel32", SetLastError = true, EntryPoint = "GetProcAddress")]
        static extern IntPtr GetProcAddressOrdinal(IntPtr hModule, IntPtr procName);

        private delegate double fDelegate(double x, double y);
        static void Main(string[] args)
        {
            var dllPath = "MyLibrary.dll";
            IntPtr dllInstance = LoadLibrary(dllPath);
            while (dllInstance == IntPtr.Zero)
            {    
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Can't load DLL " + dllPath);

                Console.ForegroundColor = ConsoleColor.Gray;
                Console.WriteLine("Write the path below...");
                dllPath = Console.ReadLine();
                dllInstance = LoadLibrary(dllPath);
            }

            string fname = "f";
            IntPtr funcPtr = GetProcAddress(dllInstance, fname);
            fDelegate fd = (fDelegate)Marshal.GetDelegateForFunctionPointer(funcPtr,
                typeof(fDelegate));
            var y = fd(1.0, 2.0);
        }
    }
}

dll:

using System;

namespace MyProj
{
    public class MyLibrary
    {
        public static double f(double x, double y) => 3 * Math.Sin(x) + 2 * Math.Cos(y);
    }
}

DLL(C++,VS2019):MyLib.h:

#pragma once
extern "C" __declspec(dllexport) double f(const double x, const double y);

MyLib.cpp:

#include "MyLib.h"
#include "pch.h"
#include <cmath>
double f(const double x, const double y)
{
    return 3 * sin(x) + 2 * cos(y);
}

PS根据MDSN的指南here

c#
  • 1 1 个回答
  • 10 Views

1 个回答

  • Voted
  1. Best Answer
    user206435
    2020-02-14T05:56:47Z2020-02-14T05:56:47Z

    您应该注意的第一件事是您的项目中使用了哪种约定:

    在此处输入图像描述

    接下来,在形成非托管导入函数的委托时,您需要添加适当的属性:

    [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
    private delegate double ImportFDelegate(double x, double y);
    

    接下来,在请求指向非托管函数的指针时,请确保传递正确的函数名称:

    就我而言:

    C:\Users\ヒミコ\source\repos\SO\Debug>dumpbin /exports MyLib.dll
    Microsoft (R) COFF/PE Dumper Version 14.24.28316.0
    Copyright (C) Microsoft Corporation.  All rights reserved.
    
    
    Dump of file MyLib.dll
    
    File Type: DLL
    
      Section contains the following exports for MyLib.dll
    
        00000000 characteristics
        FFFFFFFF time date stamp
            0.00 version
               1 ordinal base
               1 number of functions
               1 number of names
    
        ordinal hint RVA      name
    
              1    0 0001117C f = @ILT+375(_f) // Здесь указано экспортированное имя, и реальное, реальное с подчеркиванием
                                               // подробнее на MSDN https://docs.microsoft.com/ru-ru/cpp/cpp/argument-passing-and-naming-conventions?view=vs-2019
    
      Summary
    
            1000 .00cfg
            1000 .data
            1000 .idata
            1000 .msvcjmc
            2000 .rdata
            1000 .reloc
            1000 .rsrc
            6000 .text
           10000 .textbss
    
    C:\Users\ヒミコ\source\repos\SO\Debug>
    

    还要确保项目的位深度匹配,即 如果库是 x86,那么项目在 c# x86 中,与 x64 相同。

    以下是更正后的代码:

    class Program
    {
        [DllImport("kernel32", SetLastError = true, CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Winapi)]
        static extern IntPtr LoadLibrary(string lpFileName);
    
        [DllImport("kernel32", CharSet = CharSet.Ansi, SetLastError = true, CallingConvention = CallingConvention.Winapi)]
        static extern IntPtr GetProcAddress(IntPtr hModule, string procName);
    
        [DllImport("kernel32", SetLastError = true, CallingConvention = CallingConvention.Winapi)]
        [return: MarshalAs(UnmanagedType.Bool)]
        static extern bool FreeLibrary(IntPtr moduleHandle);
    
        [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
        private delegate double ImportFDelegate(double x, double y);
    
        static void Main(string[] args)
        {
            string dllPath = "MyLibrary.dll";
            IntPtr dllInstance = LoadLibrary(dllPath);
    
            while (dllInstance == IntPtr.Zero)
            {
                int errorCode = Marshal.GetLastWin32Error();
                Win32Exception exception = new Win32Exception(errorCode);
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Unable to load library {1}:\n\t{0}", exception.Message, Path.GetFileName(dllPath));
    
                Console.ResetColor();
                Console.WriteLine("Write the path below...");
                dllPath = Console.ReadLine();
                dllInstance = LoadLibrary(dllPath);
            }
    
            const string functionName = "f";
            IntPtr funcPtr = GetProcAddress(dllInstance, functionName);
    
            if (funcPtr == IntPtr.Zero)
            {
                int errorCode = Marshal.GetLastWin32Error();
                Win32Exception exception = new Win32Exception(errorCode);
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Unable to get address of function: {0}\n\t{1}", functionName, exception.Message);
                return;
            }
    
            ImportFDelegate fd = (ImportFDelegate)Marshal.GetDelegateForFunctionPointer(funcPtr, typeof(ImportFDelegate));
            double result = fd(1.0, 2.0);
    
            Console.WriteLine("Imported function return result: {0:N}", result);
    
            FreeLibrary(dllInstance);
        }
    }
    

    这是程序的实际输出:

    Unable to load library MyLibrary.dll:
            Не найден указанный модуль
    Write the path below...
    MyLib.dll
    Imported function return result: 1,69
    
    • 2

相关问题

  • 如何知道类中的方法是否属于接口?

Sidebar

Stats

  • 问题 10021
  • Answers 30001
  • 最佳答案 8000
  • 用户 6900
  • 常问
  • 回答
  • Marko Smith

    如何从列表中打印最大元素(str 类型)的长度?

    • 2 个回答
  • Marko Smith

    如何在 PyQT5 中清除 QFrame 的内容

    • 1 个回答
  • Marko Smith

    如何将具有特定字符的字符串拆分为两个不同的列表?

    • 2 个回答
  • Marko Smith

    导航栏活动元素

    • 1 个回答
  • Marko Smith

    是否可以将文本放入数组中?[关闭]

    • 1 个回答
  • Marko Smith

    如何一次用多个分隔符拆分字符串?

    • 1 个回答
  • Marko Smith

    如何通过 ClassPath 创建 InputStream?

    • 2 个回答
  • Marko Smith

    在一个查询中连接多个表

    • 1 个回答
  • Marko Smith

    对列表列表中的所有值求和

    • 3 个回答
  • Marko Smith

    如何对齐 string.Format 中的列?

    • 1 个回答
  • Martin Hope
    Alexandr_TT 2020年新年大赛! 2020-12-20 18:20:21 +0000 UTC
  • Martin Hope
    Alexandr_TT 圣诞树动画 2020-12-23 00:38:08 +0000 UTC
  • Martin Hope
    Air 究竟是什么标识了网站访问者? 2020-11-03 15:49:20 +0000 UTC
  • Martin Hope
    Qwertiy 号码显示 9223372036854775807 2020-07-11 18:16:49 +0000 UTC
  • Martin Hope
    user216109 如何为黑客设下陷阱,或充分击退攻击? 2020-05-10 02:22:52 +0000 UTC
  • Martin Hope
    Qwertiy 并变成3个无穷大 2020-11-06 07:15:57 +0000 UTC
  • Martin Hope
    koks_rs 什么是样板代码? 2020-10-27 15:43:19 +0000 UTC
  • Martin Hope
    Sirop4ik 向 git 提交发布的正确方法是什么? 2020-10-05 00:02:00 +0000 UTC
  • Martin Hope
    faoxis 为什么在这么多示例中函数都称为 foo? 2020-08-15 04:42:49 +0000 UTC
  • Martin Hope
    Pavel Mayorov 如何从事件或回调函数中返回值?或者至少等他们完成。 2020-08-11 16:49:28 +0000 UTC

热门标签

javascript python java php c# c++ html android jquery mysql

Explore

  • 主页
  • 问题
    • 热门问题
    • 最新问题
  • 标签
  • 帮助

Footer

RError.com

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

帮助

© 2023 RError.com All Rights Reserve   沪ICP备12040472号-5