I know I cannot add reference to c# dll library in Silverlight application if it's not Silverlight library. But I've a question - can I treat this dll like unmanaged code and use PInvoke like with C/C++ libraries ? I had try with sample project dll library:
namespace TestLib
{
public class TestClass
{
public static int Add(int x, int y)
{
return x + y;
}
}
}
And in my silverlight application:
[System.Runtime.InteropServices.DllImport("TestLib.dll", EntryPoint = "TestLib.Add", CallingConvention = System.Runtime.InteropServices.CallingConvention.StdCall)]
public static extern int Add(int x, int y);
but I'm getting an error while trying to invoke method:
Unable to find an entry point named 'TestLib.Add' in DLL
and if I try without namespace:
Unable to find an entry point named 'Add' in DLL
Can You point me with some hits ? Note, I've also tried to compile this dll as Silverlight application but there are some methods unsupported by Silverlight.
I think this MSDN Article is relevant to your problem. It seems to be possible, but your DLL isn't in C#, is it ? Because if it is then a PInvoke might not works.
I'd use COM for interop with your C# dll rather than trying Pinvoke. Expose some classes in you dll as COM objects, then use JavaScript to create those COM objects, and call their functions.
var progid = "TestLib.MyObject";
var TestLibObject = new ActiveXObject(progid);
var result = TestLibObject.Add(1, 2);
Once I had the JavaScript calls working with the COM object I wrapped them in a class to represent the COM object in Silverlight.
public class MyObject
{
string varName = "myObject";
public MyObject()
{
string js = "var " + varName + " = new ActiveXObject(\"TestLib.MyObject\");"
HtmlPage.Window.Eval(js);
}
public int Add(int x, int y)
{
string js = string.Format("{0}.Add({1},{3});", varName, x, y);
return (int)HtmlPage.Window.Eval(js);
}
}
You may want to refer to http://msdn.microsoft.com/en-us/library/cc645031(v=vs.95).aspx to see how manages types are passed to/from JavaScript.
If you still want to use Pinvoke you could try UnmanagedExports . It adds a DllExport attribute that you can use to expose a function to native code. You should then be able to Pinvoke this function.
In my own project I had success with using COM/JavaScript for interop in Silverlight. I haven't tried UnmanagedExports/Pinvoke in Silverlight.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.