Как SWIG в VS2010? - PullRequest
       8

Как SWIG в VS2010?

5 голосов
/ 11 мая 2011

Привет всем, я пытаюсь переключить многофайловый проект, который я сделал в VS2010 (c ++) на python.Мне удалось связать файл Python26.lib, и у меня есть SWIG, генерирующий файл .cpp оболочки для моего основного файла .cpp.Я установил свой код для сборки .dll с расширением .pyd.

Это файл .i, который у меня есть в настоящее время:

%module HiveGPS

%{
#include "ou_thread.h"
#include "HiveGPS.h"
%}


%include ou_thread.h
%include HiveGPS.h

И я получил мануал, чтобы получить файлы .py и .pyc.Теперь, насколько я понимаю, чтобы запустить мой файл .py, мне нужно связать его с моим файлом .pyd, но когда я пытаюсь использовать VS2010 для создания своего проекта с настройками, которые я перечислил выше, он жалуется на класс Thread IЯ использую:

1>------ Build started: Project: HiveGPS, Configuration: Release Win32 ------
1>Build started 5/11/2011 1:41:30 PM.
1>InitializeBuildStatus:
1>  Touching "Release\HiveGPS.unsuccessfulbuild".
1>ClCompile:
1>  HiveGPS_wrap.cpp
1>c:\users\*\desktop\hivegps\hivegps\ou_thread.h(57): error C2146: syntax error : missing ';' before identifier 'm_strName'
1>c:\users\*\desktop\hivegps\hivegps\ou_thread.h(57): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>c:\users\*\desktop\hivegps\hivegps\ou_thread.h(57): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>c:\users\*\desktop\hivegps\hivegps\ou_thread.h(64): error C2146: syntax error : missing ';' before identifier 'getName'
1>c:\users\*\desktop\hivegps\hivegps\ou_thread.h(64): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>c:\users\*\desktop\hivegps\hivegps\ou_thread.h(64): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>c:\users\*\desktop\hivegps\hivegps\ou_thread.h(64): warning C4183: 'getName': missing return type; assumed to be a member function returning 'int'
1>c:\users\*\desktop\hivegps\hivegps\ou_thread.h(98): error C2146: syntax error : missing ';' before identifier 'm_strName'
1>c:\users\*\desktop\hivegps\hivegps\ou_thread.h(98): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>c:\users\*\desktop\hivegps\hivegps\ou_thread.h(98): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>c:\users\*\desktop\hivegps\hivegps\ou_thread.h(104): error C2146: syntax error : missing ';' before identifier 'getName'
1>c:\users\*\desktop\hivegps\hivegps\ou_thread.h(104): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>c:\users\*\desktop\hivegps\hivegps\ou_thread.h(104): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>c:\users\*\desktop\hivegps\hivegps\ou_thread.h(104): warning C4183: 'getName': missing return type; assumed to be a member function returning 'int'
1>c:\users\*\desktop\hivegps\hivegps\ou_thread.h(115): error C2146: syntax error : missing ';' before identifier 'msg'
1>c:\users\*\desktop\hivegps\hivegps\ou_thread.h(115): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>c:\users\*\desktop\hivegps\hivegps\ou_thread.h(115): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>c:\users\*\desktop\hivegps\hivegps\ou_thread.h(118): error C2146: syntax error : missing ';' before identifier 'getMessage'
1>c:\users\*\desktop\hivegps\hivegps\ou_thread.h(118): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>c:\users\*\desktop\hivegps\hivegps\ou_thread.h(118): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>c:\users\*\desktop\hivegps\hivegps\ou_thread.h(118): warning C4183: 'getMessage': missing return type; assumed to be a member function returning 'int'
1>c:\users\*\desktop\hivegps\hivegps\ou_thread.h(51): error C2011: 'openutils::Thread' : 'class' type redefinition
1>          c:\users\*\desktop\hivegps\hivegps\ou_thread.h(51) : see declaration of 'openutils::Thread'
1>c:\users\*\desktop\hivegps\hivegps\ou_thread.h(93): error C2011: 'openutils::Mutex' : 'class' type redefinition
1>          c:\users\*\desktop\hivegps\hivegps\ou_thread.h(93) : see declaration of 'openutils::Mutex'
1>c:\users\*\desktop\hivegps\hivegps\ou_thread.h(113): error C2011: 'openutils::ThreadException' : 'class' type redefinition
1>          c:\users\*\desktop\hivegps\hivegps\ou_thread.h(113) : see declaration of 'openutils::ThreadException'
1>c:\users\*\desktop\hivegps\hivegps\HiveGPS.h(29): error C2504: 'openutils::Thread' : base class undefined
1>c:\users\*\desktop\hivegps\hivegps\HiveGPS.h(53): error C2079: 'HiveGPS::readWriteMutex' uses undefined class 'openutils::Mutex'
1>HiveGPS_wrap.cpp(3086): error C2027: use of undefined type 'openutils::Thread'
1>          c:\users\*\desktop\hivegps\hivegps\ou_thread.h(51) : see declaration of 'openutils::Thread'
1>HiveGPS_wrap.cpp(3086): fatal error C1903: unable to recover from previous error(s); stopping compilation
1>
1>Build FAILED.
1>
1>Time Elapsed 00:00:02.10
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

Все эти ошибки (за исключением последней) в основном говорят о том, что класс String реализован каким-либо образом, противоречит ли это определению Python класса String?Последняя ошибка - жалоба на класс Thread, может ли это быть той же проблемой?

Все это говорит: может кто-нибудь сказать мне, что я делаю неправильно, или, еще лучше, указать мне учебник о том, каксделать это для VS2010 (сайт SWIG предназначен для 2008 года).

И если это невозможно, могу ли я каким-то образом связать сгенерированный мной файл .py с файлом .dll?

Извините за длинное объяснение, но я немного растерялся, поэтому решил все объяснить.

Ответы [ 2 ]

11 голосов
/ 25 мая 2011

Хорошо, я использую swig и VS2010 без проблем ...

В вашем случае это больше похоже на проблемы со связыванием.Помимо проверки библиотек, не забудьте проверить 32-64-битные библиотеки, которые вы связываете.Попробуйте связать все как цель x86 как отказоустойчивую.И не используйте AnyCpu .


Как использовать SWIG под VS2010.

позволяет определить, хотите ли вы получить mylib.pyИтак, вы создали некоторые файлы интерфейса SWIG с mylib.i в качестве «основного» файла.Я предполагаю, что у вас уже есть решение с проектом с вашими классами C ++.

(1) Сначала создайте проект C ++ для интерфейса SWIG.Используйте Visual C ++ -> проект библиотеки классов, который должен создать заглушку C ++ DLL.Я положил туда все .i файлы.И установите Visual Studio, чтобы выделить .i как .h - это удобно.

(1.1) Добавить файл mylib_wrap.cxx в проект (создать пустой файл, пока swig еще не создал его)

(2)
a) Нажмите правую кнопку над mylib.i, выберите свойства.
b) установите ItemType как «Инструмент пользовательской сборки».
В окне шага пользовательской сборки:
c) Поле командной строки должночто-то вроде:

echo In order to function correctly, please ensure the following environment variables are
correctly set: 
echo PYTHON_INCLUDE: %PYTHON_INCLUDE% 
echo PYTHON_LIB: %PYTHON_LIB% 
echo on 
C:\swig\swig.exe -c++ -python %(FullPath) 

измените C: \ swig \ swig.exe на свой путь к SWIG

d) В поле Outputs:

$(InputName)_wrap.cxx

Custom build window

(3) Перейти к свойствам этого проекта:

a) Вкладка C ++ -> Дополнительные каталоги включения
добавить $ (PYTHON_INCLUDE);...

c) Linker -> Выходной файл
Path-You-Needed \ _ mylib.pyd

d) Linker -> Включить инкрементное связывание
, установленное как Нет (/ INCREMENTAL: NO)

e) Linker -> Ввод -> Дополнительные зависимости
add $ (PYTHON_LIB); ...

f) C / C ++ -> Предварительно скомпилированные заголовки : Отключите предварительно скомпилированные заголовки, установите ** Не использовать предварительно скомпилированные заголовки * и удалите файлы stdafx после

g) General tab.Просто убедитесь, что они установлены:
Тип конфигурации = Динамическая библиотека (.dll)
Набор символов = Использовать набор символов Unicode
Поддержка времени выполнения общего языка = Нет поддержки времени выполнения общего языка

Компилируется.

PS И не забудьте также установить переменные% PYTHON_INCLUDE% и% PYTHON_LIB% в вашей системе.

0 голосов
/ 02 июня 2011

Кажется, что в файле ou_thread.h отсутствует #include.

Более того, переопределение типа «класс» может указывать на то, что у вас нет ничего похожего на

#ifndef __ou_thread_h__
#define __ou_thread_h__

// your stuff, classes, etc.

#endif

в вашем ou_thread.h

Это предположение ...

...