wp7中调用native代码的方法

时间:2021-08-06 13:49:36

What I discovered today was some FUNKY code that Samsung had created to set the Network properties of a Windows Phone 7 handset.  Taking a peek under the skirt, I noticed something unreal.  The application has unmanaged DLL’s inside the XAP file!!!

wp7中调用native代码的方法

Ok, you’re thinking, so what, this isn’t anything special.  All they’ve done is add them manually into the project as a content build action.

True, they have done that, but what’s next is even more UNREAL.

Looking “into” NetworkProfile.dll (Silverlight managed code) reveals the TRUTH we’ve all been waiting to hear, can I run a “native” app for Windows Phone 7?  The answer is TRUE (with some caveats).

There’s a funky DLL called Microsoft.Phone.InteropServices that lives in the GAC of all WP7 handsets that we need to enable COM access.

wp7中调用native代码的方法

Now for this blog post, we’re only going to cover the “ComBridge” class in the above picture.  When you open it in reflector it’s just an empty static method.  But it’s magic is hidden.

Now to use this DLL in our application you can’t simply add it as a reference,you need to load the Assembly via reflection,and call its static methods.

Assembly a = Assembly.Load("Microsoft.Phone.InteropServices, Version=7.0.0.0, Culture=neutral, PublicKeyToken=24eec0d8c86cda1e");

Ok, now we’ve loaded it.  We need to get the type (from the namespace), get the method and invoke it.

Type comBridgeType = a.GetType("Microsoft.Phone.InteropServices.ComBridge");
MethodInfo dynMethod = comBridgeType.GetMethod(
"RegisterComDll", BindingFlags.Public | BindingFlags.Static);
dynMethod.Invoke(
null, new object[] { "Assembly.dll", new Guid("SomeGuidHere") });

Ok, now we’re almost ready.  We need to clear ALL capabilities in WMAppManifest.xml and add the following line.

<Capability Name="ID_CAP_INTEROPSERVICES"/>

Once you’ve done that, add a blank XML file in the root of the app called “WMInteropManifest.xml” and add the following content to it.

<?xml version="1.0" encoding="UTF-8"?>
<Interop>
</Interop>

Yes I’m aware the tags are empty, they’re not required.  Once you’ve done all that, right click and deploy your app.  Before this will work, I’ve found you need to reboot your device for it to actually work.

That’s all for now, I’ll be posting more this weekend about how you can get access to the RIL (Radio Interface Layer), Registry & even access to the file system.

Above I mentioned some “caveats”.  Sure you’re now loading native DLL’s, but your application is STILL running as a managed instance, and you are still bound to the normal restrictions from the OS.  You will still get tombstoned, killed etc.

这样才Windows Phone中就可以调用Win32 DLL了,也就可以在Windows Phone中调用C/C++写的代码了