为什么我需要使用EntryPoint属性定义DLLImport [英] Why do I need to define DLLImport with EntryPoint attribute

查看:621
本文介绍了为什么我需要使用EntryPoint属性定义DLLImport的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在遍历 SWig 生成的包装器时,我发现PInvokes没有定义任何入口点,但某些地方确实有一个入口点.那么它们之间有什么区别呢?什么时候需要定义一个EntryPoint,什么时候不需要?

While going through SWig generated wrappers, I find that the PInvokes don't have any entry point defined, but some places do have an entry point. So what is the difference between them? When do I need to define an EntryPoint, and when do I not need to?

没有EntryPoint的定义:

[DllImport("Kernel32.dll", CharSet = CharSet.Unicode)]
public static extern bool ReadFile(
        HandleRef hndRef,
        StringBuilder buffer,
        int numberOfBytesToRead,
        out int numberOfBytesRead,
        int flag);  

Entrypoint定义:

[DllImport("Kernel32.dll", CharSet = CharSet.Unicode, EntryPoint = "ReadFile")]
public static extern bool ReadFile2(
        HandleRef hndRef,
        StringBuilder buffer,
        int numberOfBytesToRead,
        out int numberOfBytesRead,
        Overlapped2 flag);

为什么功能必须像public static extern一样必须是static?我以为extern告诉编译器此方法是在外部定义的?

Also why does the function have to be static as in public static extern? I assume that extern is telling the compiler that this method is defined externally?

推荐答案

会导致运行时尝试调用名为ReadFile2的函数(不存在).

The EntryPoint field serves to tell the .NET runtime which function to call from the DLL being invoked; if it's not set, the default is the same name that the .NET method declaration has. In your second example, omitting EntryPoint = "ReadFile" would result in the runtime trying to call a function named ReadFile2 (which does not exist).

原型需要具有static extern 修饰符,因为规范就是这样.不必是public;控制方法的可见性完全取决于您.

The prototype needs to have the static and extern modifiers because the specification says so. It does not need to be public; controlling the visibility of the method is entirely up to you.

这篇关于为什么我需要使用EntryPoint属性定义DLLImport的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆