У меня есть статическая библиотека, написанная на C++, которую я хочу сделать доступной для приложений Windows 8 и Windows Phone 8, написанных на .NET.Share static lib в приложениях Win8 и WP8
Я хотел бы, чтобы свести к минимуму число отдельных проектов, чтобы поддерживать путем создания мое решение что-то вроде следующего:
Попытка # 1: Только проекты пользовательского интерфейса являются конкретной платформы
MySolution.sln
|
+- Library (virtual folder to group projects below)
| |
| +- LegacyLib.vcxproj Static Library project - Platform-independant, native C++ code using STL & CRT. Just enough C++/CX to make some types available to .NET and expose a few static methods.
| |
| +- LegacyPcl.csproj Portable Class Library project - References LegacyLib, adds some types, wrappers, interfaces, etc. written in C#.
|
+- SampleApp (virtual folder to group projects below)
|
+- CommonAppSrc Platform-independant C# source code (e.g. MVVM classes for Model and ViewModel).
|
+- SampleApp_Win8.csproj Platform-specific App project - References LegacyPcl, includes files from CommonAppSrc using "Add as Link".
|
+- SampleApp_Wp8.csproj Platform-specific App project - References LegacyPcl, includes files from CommonAppSrc using "Add as Link".
Проблема: Кажется, что Portable Class Libraries не поддерживают включение собственного кода на C++ в любой форме.
Предлагаемый способ включения собственного C++ в ваши приложения для Windows 8 и Windows Phone 8 заключается в создании компонентов Windows Runtime. К сожалению, проекты WRC, ориентированные на Win8 и Wp8, - разные типы проектов; нет возможности создать компонент Runtime Windows, предназначенный для нескольких платформ.
Таким образом, создание проекта среды выполнения Windows компонентов для каждой целевой платформы дает следующие:
Попытка # 2 - UI проекты конкретной платформы, и поэтому LegacyLib обертка
MySolution.sln
|
+- Library (virtual folder to group projects below)
| |
| +- LegacyLib.vcxproj Static Library project - Platform-independant, native C++ code using STL & CRT. Just enough C++/CX to make some types available to .NET and expose a few static methods.
| |
| +- LegacyWrc_Win8.csproj Platform-specific Windows Runtime Component project - References LegacyLib, adds some types, wrappers, interfaces, etc. written in C#.
| |
| +- LegacyWrc_Wp8.csproj Platform-specific Windows Runtime Component project - References LegacyLib, adds some types, wrappers, interfaces, etc. written in C#.
|
+- SampleApp (virtual folder to group projects below)
|
+- CommonAppSrc C# source code (e.g. Model and ViewModel classes).
|
+- SampleApp_Win8.csproj Platform-specific App project - References LegacyWrc_Win8, includes files from CommonAppSrc using "Add as Link".
|
+- SampleApp_Wp8.csproj Platform-specific App project - References LegacyWrc_Wp8, includes files from CommonAppSrc using "Add as Link".
Проблема: Когда я пытаюсь ссылаться на LegacyLib из проекта LegacyWrc_Win8; Я вижу следующее предупреждение:
Adding reference to 'LegacyLib' is not recommended because it is not compatible with Windows Store Apps.
среда сборки говорит, что, чтобы сделать статические библиотеки LegacyLib совместимы с моей Win8 среды выполнения Windows Component, я должен включить поддержку Windows Store App в конфигурации проекта LegacyLib (игнорируя предупреждение только приводит к ошибке позже):
- Свойства проекта>Свойства конфигурации>Общие>Defaults проекта
- Установка Поддержка Windows Store App в Да
Далее, когда я пытаюсь сделать то же самое с проектом LegacyWrc_Wp8, я получаю следующее сообщение об ошибке:
A reference to 'LegacyLib' cannot be added because the two projects target different platforms.
Итак, статическая библиотека, совместимая с Windows 8, сделала это несовместимо с телефоном Windows 8.
Похоже, что просто невозможно создать единую статическую библиотеку, которая может быть использована этими двумя разными платформами, хотя сама библиотека не содержит кода для конкретной платформы.
Я не обязательно должен поддерживать параллельные версии исходного кода, но мне нужно создать/поддерживать два отдельных проекта, каждый из которых создает версию статической библиотеки на платформе.
Мое решение теперь имеет конкретной платформы версии каждый проект:
Покушение # 3 - КАЖДЫЙ ПРОЕКТ платформозависимый
MySolution.sln
|
+- Library (virtual folder to group projects below)
| |
| +- NativeCode (virtual folder to group projects below)
| | |
| | +- CommonLibSrc Native C++ source code using STL & CRT. Just enough C++/CX to make some types available to .NET and expose a few static methods.
| | |
| | +- LegacyLib_Win8.vcxproj Platform-specific Static Library project - Includes files from CommonLibSrc using "Add as Link".
| | |
| | +- LegacyLib_Wp8.vcxproj Platform-specific Static Library project - Includes files from CommonLibSrc using "Add as Link".
| |
| +- DotNetWrapper (virtual folder to group projects below)
| |
| +- CommonWrcSrc Platform-independant C# source code (types, wrappers, interfaces, etc. for LegacyLib support) for the Windows Runtime Component projects.
| |
| +- LegacyWrc_Win8.csproj Platform-specific Windows Runtime Component project - References LegacyLib_Win8, includes files from CommonWrcSrc using "Add as Link".
| |
| +- LegacyWrc_Wp8.csproj Platform-specific Windows Runtime Component project - References LegacyLib_Wp8, includes files from CommonWrcSrc using "Add as Link".
|
+- SampleApp (virtual folder to group projects below)
|
+- CommonAppSrc Platform-independant C# source code (e.g. Model, ViewModel).
|
+- SampleApp_Win8.csproj Platform-specific App project - References LegacyWrc_Win8, includes files from CommonAppSrc using "Add as Link".
|
+- SampleApp_Wp8.csproj Platform-specific App project - References LegacyWrc_Wp8, includes files from CommonAppSrc using "Add as Link".
Проблема: Ни что я не могу видеть так далеко (за исключением того, что это уродливое и более высокое обслуживание).
Кстати, я рассмотрел возможность использования Build Configurations, но они уже используются для сочетания Debug/Release и x86/ARM. Добавление Win8/Wp8 в микс просто удваивает конфигурации снова, и вы переместились, а не уменьшили нагрузку на обслуживание.
Я что-то упустил? Похоже, это то, что нужно делать. Кто-нибудь еще прошел через это и придумал альтернативные/лучшие способы сделать это?
EDIT ДЛЯ ПОЛНОТЫ
Вот что я в конечном итоге делает ...
MySolution.sln
|
+- LegacyApiLib (virtual folder to group projects below)
| |
| +- CommonCppSource Common C++ source code used by LegacyWrc_*.vcxproj projects
| | below
| |
| +- LegacyPcl.csproj Portable class library with C# API interfaces only; no
| | implementation classes.
| |
| +- LegacyWrc_Win8.vcxproj Platform-specific Windows Runtime Component project - includes
| | legacy C++ files, and uses C++/CX to expose static methods and
| | classes to .NET in Win8.
| |
| +- LegacyWrc_Wp8.vcxproj Platform-specific Windows Runtime Component project - includes
| legacy C++ files, and uses C++/CX to expose static methods and
| classes to .NET in WP8.
|
+- SampleApp (virtual folder to group projects below)
|
+- SampleAppBL.csproj Portable class library containing the app's business logic.
| References LegacyPcl.csproj for legacy API interface definitions.
| Business logic is written against those interfaces; never against
| specific classes. The Win8 or WP8 apps will reference the
| appropriate Windows Runtime Component project, create or register
| the concrete classes that implement the legacy API interface, and
| either pass it into the BL or register it with IOC mechanism. In
| this way, SampleAppBL.csproj never has to know about (or
| reference) any of the WRC projects.
|
+- SampleAppUI_Win8.csproj Platform-specific App project - References LegacyWrc_Win8.vcxproj
| and SampleAppBL. Contains minimal platform-specific Win8 UI code.
|
+- SampleAppUI_Wp8.csproj Platform-specific App project - References LegacyWrc_Wp8.vcxproj
and SampleAppBL. Contains minimal platform-specific WP8 UI code.
я понял, что несколько вспомогательных классов, что экспорт LegacyApiLib может быть написаны на управляемом C++ вместо C#. Это означало, что я мог просто связать их с проектами WRC, что немного упростило ситуацию.