php - SWIG fatal error : can not redeclare class

标签 php class swig declaration

我在使用 swig 将我的 C++ 类包装在 PHP 中时遇到问题: 我的类在头文件中声明如下:

#include <string.h>
using namespace std;
class Ccrypto
{
  int retVal;
public:
  int verify(string data, string pemSign, string pemCert);
  long checkCert(string inCert, string issuerCert, string inCRL);
  int verifyChain(string inCert, string inChainPath);
  int getCN(string inCert, string &outCN);
};

这些方法中的每一个都包含几个函数。
我的接口(interface)文件如下:

%module Ccrypto
%include <std_string.i>
%include "Ccrypto.h"
%include "PKI_APICommon.h"
%include "PKI_Certificate.h"
%include "PKI_Convert.h"
%include "PKI_CRL.h"
%include "PKI_TrustChain.h"

%{
#include "Ccrypto.h"

#include "PKI_APICommon.h"
#include "PKI_Certificate.h"
#include "PKI_Convert.h" 
#include "PKI_CRL.h"
#include "PKI_TrustChain.h"
%}    

我生成了 Ccrypto.so 文件,没有任何错误。但是当我在我的代码中使用这个类时,我遇到了这个错误:

Fatal error: Cannot redeclare class Ccrypto in /path/to/my/.php file

当我检查 Ccrypto.php 文件时,我发现 class Ccrypto 被声明了两次。我的意思是我有:

Abstract class Ccrypto {
....
}

class Ccrypto {
...
}

为什么 SWIG 会为我的类生成两个声明?

最佳答案

问题是您有一个与模块同名的类(%module 或命令行上的 -module)。 SWIG 将 C++ 中的自由函数公开为具有模块名称的抽象类的静态成员函数。我认为这是为了模仿 namespace 。因此,生成的 PHP 将包含两个类,如果您是一个与模块同名的类并且具有任何非成员函数,则一个是抽象类。

您可以通过以下方式进行测试:

%module test

%inline %{
class test {
};

void some_function() {
}
%}

这会产生您报告的错误。

令我略感惊讶的是,SWIG 在看到 PHP 运行时错误之前没有对此发出警告。它在生成 Java 时为同一接口(interface)提供以下错误:

Class name cannot be equal to module class name: test

有几种可能的方法可以解决这个问题:

  1. 重命名模块
  2. 重命名代码库中的类。
  3. 重命名类(使用 %rename):

    %module test
    
    %rename (test_renamed) test;
    
    %inline %{
    class test {
    };
    
    void some_function() {
    }
    %}
    
  4. 隐藏自由函数:

    %ignore some_function;
    

关于php - SWIG fatal error : can not redeclare class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12446905/

相关文章:

html - 容器内的CSS中心div?

javascript - 如何在 Javascript 函数中循环?

javascript - AJAX 和 php 脚本后添加的表单元素未传输到 $_POST

javascript - Jquery 应用类和删除类

python - PySide如何在QDialog类对象中组合多个布局

python - 如何让我的 SWIG 扩展模块与 Pickle 一起工作?

php - isset 不适用于表单提交(实际上是数据库问题)

php - 使用 preg_replace 进行可变长度掩码

c++ - 有没有办法使用 SWIG 将不同的数组类型从 python 传递到 c++?

python - python 导演使用的 swig 错误 c++