如何从Windows Phone上的C#项目调用C ++ DLL函数

时间:2015-04-20 03:28:46

标签: c# silverlight windows-phone-8 dll windows-phone-8.1

主题看似重复,但不是:

主要项目是:

C# Project -> WP8.1 Silverlight
or
C# Project -> WP8.1 RT

C ++ DLL项目有3个选项:

C++ ProjectA ->Windows Runtime Component (Windows Phone Silverlight 8.1) <- this is DLL
C++ ProjectB ->DLL (Windows Phone Silverlight 8.1)
C++ PorjectC ->DLL (Windows Phone)  <- (WinRT 8.1)

好的,我没有任何语法问题,网上有很多教程,比如

// In C#
[DllImport("WRCWP81SLd.dll", EntryPoint = "DllWP81SLFunc")]

// In C++
extern "C" __declspec(dllexport) int DllWP81SLFunc();

问题是,如何将dll添加到C#项目中, 如何将dll项目连接到C#项目以让C#检测DLL中的C ++函数?

我尝试添加项目的引用,就像ppl在一些教程中所说的那样(它适用于C ++到C ++)

但是 将ProjectA,ProjectB,ProjectC添加到[C#Project - &gt; WP8.1 Silverlight]

除了将[WinRuntimeComponent Silverlight8.1]添加到[WP8.1 Silverlight]

之外全部失败

将ProjectA,ProjectB,ProjectC添加到[C#Project - &gt; WP8.1 RT]

全部失败

A reference to 'DLLWP81RT' could not be added.

关于唯一的suceed - [C#WP8.1 Silverlight] - [C ++ Windows运行时组件Silverlight 8.1],它在运行时崩溃了。

// declare
[DllImport("WRCWP81SLd.dll", EntryPoint = "DllWP81SLFunc", CallingConvention = CallingConvention.StdCall)]
public static extern int DllWP81SLFunc();

// crash at this line, couldn't detect the function
int w = DllWP81SLFunc(); <- crash

所以我的问题是:      用C#项目连接C ++ DLL的正确方法是什么?      如何让C#在WindowsPhone 8.1 RT / Silverlight项目中检测C ++函数?

//-------------------------------------------------------------------------------------
//-----------The beautiful devider
//-------------------------------------------------------------------------------------

回答David Heffernan:

在[C#WP8.1 Silverlight]项目

尝试添加[C ++ DLL WP8.1 RT]

Unable to add the reference to DLLWP81RT.A reference to 'DLLWP81RT' could not be added.
The method or operation is not implemented.

尝试添加[C ++ DLL WP8.1 Silverlight]时

Unable to add the reference to DLLWP81SL.A reference to 'DLLWP81SL' could not be added.
The method or operation is not implemented.

// -------------------------------------------

在[C#WP8.1 WRT]项目

尝试添加[C ++ DLL WP8.1 RT]作为参考时

A reference to 'DLLWP81RT' could not be added

尝试添加[C ++ DLL WP8.1 Silverlight]作为参考时

A reference to 'DLLWP81SL' could not be added

尝试添加[C ++ WindowsRuntimeComponent WP8.1]作为参考

A reference to 'WRCWP81SL' could not be added

所以,到目前为止,

我只能将[C ++ WindowsRuntimeComponent WP8.1]添加到[C#WP8.1 Silverlight]项目中 但是在调用C风格函数时失败了 -

An exception of type 'System.NotSupportedException' occurred in 'YYYY.DLL' but was not handled in user code
Additional information: DllImport cannot be used on user-defined methods

1 个答案:

答案 0 :(得分:0)

好的,我找到了答案。

没有办法添加&#c; un_managed C ++ DLL项目&#39;作为对管理的C#项目的参考&#39;。

正确的连接方法是手动将C ++项目中的* .dll添加到C#项目并执行P / Invoke。

但是在电话会议上仍然失败了,我不知道为什么。 :-P

//我找到了原因:

更多细节, 请看一下我创建的这个主题:

How to Call [Unmanaged C++ DLL func] from [C# WP8.1 WRT/SL] project