Benjamin
Benjamin

Reputation: 900

PInvoke Libraries

I've seen a lot of examples on the web using PInvoke to do low-level platform specific operations, but they all use basically the same method prototypes each time. Then, looking at the Microsoft Reference Source, each assembly defines all the PInvoke functions that assembly needs, and always marks the classes as internal. My question is "Why?".

Why, in a world where we're trying to reuse as much code as possible, do we have to rewrite the signature for CreateFile for every project we need it in? What are the issues with writing a couple of standardized WinAPI libraries? I assume there are some issues, because for the most part it hasn't been done, or the projects have been quickly abandoned.

Upvotes: 0

Views: 660

Answers (2)

Andrew Arnott
Andrew Arnott

Reputation: 81847

The assemblies that mark these p/invoke signatures as internal do so because their purpose is to provide a higher level of abstraction. And in many cases to be cross platform (including platforms on which the P/Invoke methods don't exist). Making them internal ensures that callers focus on the higher level abstraction that works everywhere.

Why, in a world where we're trying to reuse as much code as possible, do we have to rewrite the signature for CreateFile for every project we need it in? What are the issues with writing a couple of standardized WinAPI libraries?

Such a library might get rather large with metadata and most users of the library probably only need a small fraction of what it would contain. But as I sympathize with the desire for code reuse and a reliable source of p/invoke signatures, I started a P/Invoke library on GitHub that's meant to include all the P/Invoke signatures you could want (from Win32 at least). It's sort of like pinvoke.net, except the code always compiles, and you can consume it via a nuget package. I hope you find it useful to you in what it sounds like you're trying to do.

Upvotes: 1

Ardianto Suhendar
Ardianto Suhendar

Reputation: 131

The marking of internal is by design, that they don't want those declarations to be exposed to the outside assemblies.

The .NET framework are meant to wrap around the Win32 APIs so users don't need to use them directly, but they can deal with a level of abstraction above. If they expose the API below, I don't think its a good design of an abstraction layer. After a few layers it would be exposing too many functions below.

I think the issue is between encapsulation and reusability. Encapsulation indeed reduces reusability, but it improves maintainability.

Upvotes: 0

Related Questions