gpt4 book ai didi

interface - 避免 swig 中出现 'nothing known about [parent] class...' 错误

转载 作者:行者123 更新时间:2023-12-04 17:58:06 27 4
gpt4 key购买 nike

假设我在头文件 A.h 中有两个类 A

// A.h
class A {
public:
void foo();
};

和头文件 B.h 中的 B
// B.h
class B : public A {
public:
void bar()
};

我想为 B 类生成一个 Swig 包装器。接口(interface)文件如下所示。
B.i
%{
#include "B.h"
%}

%include B.h

运行 swig 时,它会退出并显示一条错误消息“对 A 一无所知”,这很清楚,因为 B 继承自 A,因此 swig 必须知道 A 才能生成接口(interface)。让我们进一步假设 A.h 中有一些东西是 swig 解析器无法解析的,并且当它看到这些东西时会产生错误。我突然决定,我实际上不仅需要界面中的 bar 而不是 foo。有没有办法告诉 swig,它实际上并不看 A.h,因为我真的不需要 B 从 A 继承的东西?

最佳答案

我把一个例子放在一起,只得到一个警告,说对 A 一无所知。扩展仍然可以很好地构建,并且可以在不知道 A 的 bar() 的情况下调用 B 的 foo()。这是我为 Windows 生成 Python 扩展的示例:

构建输出

C:\example>nmake /las
b.cpp
a.cpp
Generating Code...
Creating library b.lib and object b.exp
B.h(12) : Warning 401: Nothing known about base class 'A'. Ignored.
b_wrap.cxx
Creating library _b.lib and object _b.exp

示例使用
Python 2.6.6 (r266:84297, Aug 24 2010, 18:46:32) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import b
>>> b.B().bar()
In B::bar()
>>> b.B().foo()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "b.py", line 73, in <lambda>
__getattr__ = lambda self, name: _swig_getattr(self, B, name)
File "b.py", line 54, in _swig_getattr
raise AttributeError(name)
AttributeError: foo

文件


#pragma once

#ifdef DLL_EXPORTS
#define DLL_API __declspec(dllexport)
#else
#define DLL_API __declspec(dllimport)
#endif

class DLL_API A
{
public:
void foo();
};

b.h
#pragma once

#ifdef DLL_EXPORTS
#define DLL_API __declspec(dllexport)
#else
#define DLL_API __declspec(dllimport)
#endif

#include "a.h"

class DLL_API B : public A
{
public:
void bar();
};

a.cpp
#include <stdio.h>
#define DLL_EXPORTS
#include "a.h"

void A::foo()
{
printf("In A::foo()\n");
}

b.cpp
#include <stdio.h>
#define DLL_EXPORTS
#include "b.h"

void B::bar()
{
printf("In B::bar()\n");
}


%module b

%begin %{
#pragma warning(disable:4100 4127 4706)
%}

%{
#include "B.h"
%}

%include <windows.i>
%include "B.h"

生成文件
_b.pyd: b.dll b_wrap.cxx
cl /nologo /EHsc /LD /W4 b_wrap.cxx /I c:\Python26\include /Fe_b.pyd -link /nologo /libpath:c:\Python26\libs b.lib

b_wrap.cxx: b.i
swig -c++ -python b.i

b.dll: a.cpp b.cpp
cl /nologo /LD /W4 b.cpp a.cpp

关于interface - 避免 swig 中出现 'nothing known about [parent] class...' 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4483614/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com