Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Building NPAPI plugin in C#

Attempting to build a C# NPAPI plugin I have found a tutorial which describes that your dll needs to implement a number of methods such as NP_GetEntryPoints , NP_Initialize and NPP_New along with a number of others.

However what I want to understand is if I can simply mirror these method names and construct equivalent datastructures as described in the article (like _NPPluginFuncs) in C# and everything will work?

Could someone please be kind enough to provide some guidance? Is it possible to build a NPAPI plugin in C# and if so what are the basic steps involved?

like image 940
Maxim Gershkovich Avatar asked Jul 03 '12 10:07

Maxim Gershkovich


2 Answers

As stated in the documentation:

A NPAPI browser plugin is, at it’s core, simply a DLL with a few specific entry points

That means you need to export some function from a regular dll, that is done usually in C/C++. Unfortunately it is not possible to expose any entry point from a plain C# dll, but look at this answer, with some effort it appear to be possible to trick some export by some sort of post build tool.

In any case don't expect to pass too much complicated data structures from/to the plugin interfaces, it will be a pain. If you are interested in doing more research the keywork to use is "reverse P/Invoke", in analogy with direct P/Invoke that is calling regular dll from managed world.

The reason a C# dll can't expose directly "entry points" is that entry point are actually just some address inside the dll poiting to some assembly code immediately executable. C# dll are different kind of beast: they are just files containing IL that is compiled "Just In Time" and indeed such compilation is forced AFAIK with some OS tricks. This is the reason reverse P/Invoke is not starightforward at all.

like image 95
Felice Pollano Avatar answered Sep 18 '22 11:09

Felice Pollano


As Georg Fritzsche says in his comment:

NPAPI plugins are basically DLLs with a few required C-exports

and there is no built-in way to export functions (in the C-export sense) from an assembly written in C#.

Some of your options are:

  1. A mixed-mode C++ assembly which can export the functions directly. This could have implications for hosting the CLR in your plugin's host process.
  2. A small native DLL which hosts the exports, then uses COM interop to delegate to a C# assembly containing the plugin functionality. The "official" way to do so-called "reverse p/invoke".
  3. An intriguing project which post-processes your fully-managed assembly, turning static methods marked with a custom attribute into named function exports. (I have no affiliation with this project; I stumbled across it after I got to wondering whether anyone had improved on the COM interop way of doing things.)
like image 35
anton.burger Avatar answered Sep 18 '22 11:09

anton.burger