我是Swig的新手,我需要帮助来调试这个错误。
我的动机是想用Swig,C++,Perl创建一个耗时较少的日志系统。但是我在通过swig把Perl的字符串参数传给C++时出现了错误。
我把我的全部代码和错误放在下面,请帮我解决这个问题。以后谢谢。
Logger.cpp
#include <stdexcept>
#include <string>
#include <ctime>
#include "Logger.h"
using namespace std;
Logger* Logger::pInstance = nullptr;
Logger& Logger::instance()
{
lock_guard<mutex> guard(sMutex);
printf("instance");
if (pInstance == nullptr)
pInstance = new Logger();
return *pInstance;
}
void Logger::Cleanup()
{
lock_guard<mutex> guard(Logger::sMutex);
delete Logger::pInstance;
Logger::pInstance = nullptr;
}
Logger::Logger()
{
printf("Constructor\n");
mOutputStream.open("log.out", ios_base::app);
if (!mOutputStream.good()) {
throw runtime_error("Unable to initialize the Logger!");
}
}
void Logger::log(const string& inMessage, const string& inLogLevel)
{
lock_guard<mutex> guard(sMutex);
logHelper(inMessage, inLogLevel);
}
void Logger::logHelper(const std::string& inMessage, const std::string& inLogLevel)
{
mOutputStream << "[ " << current_time() << " ]" << inLogLevel << ": " << inMessage << endl;
}
string Logger::current_time()
{
time_t rawtime;
struct tm * timeinfo;
char buffer[80];
time (&rawtime);
timeinfo = localtime(&rawtime);
strftime(buffer,sizeof(buffer),"%d-%m-%Y %H:%M:%S",timeinfo);
std::string str(buffer);
return str;
}
Logger::~Logger(){
printf("deconstructor\n");
mOutputStream.close();
}
记录仪.h
#ifndef LOGGER_H_
#define LOGGER_H_
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <mutex>
class Logger
{
public:
Logger();
~Logger();
Logger& instance();
void log(const std::string& inMessage,
const std::string& inLogLevel);
protected:
static Logger* pInstance;
std::ofstream mOutputStream;
void Cleanup();
void logHelper(const std::string& inMessage,
const std::string& inLogLevel);
std::string current_time();
private:
std::mutex sMutex;
};
#endif
记录仪.i
%module Logger
%{
#include "Logger.h"
%}
%include "Logger.h"
ch.pl
use strict;
use warnings;
use Cwd qw( abs_path );
use File::Basename qw( dirname );
use lib dirname(abs_path($0));
use Logger;
my $p=new Logger::Logger();
$p->instance();
$p->log("test message");
错误信息*
TypeError in method 'Logger_log', argument 2 of type 'std::string' at ch1.perl line 19.
你需要为 std::string
在你的接口文件中,这样SWIG就知道如何处理类型了,请参见 手册第9.4章:
9.4.1 std::string 该
std_string.i
库提供了用于转换C++的类型图std::string
对象与目标脚本语言中的字符串之间的转换。
%module Logger
%include "std_string.i"
%{
#include "Logger.h"
%}
%include "Logger.h"
如果我使用这个并运行 ch.pl
像这样。
use strict;
use warnings;
use lib '.';
use Logger;
my $p = Logger::Logger->new();
$p->instance();
$p->log("test message", "DEBUG");
我得到了输出。
Constructor
instanceConstructor
deconstructor
内容是... log.out
文件是。
[ 22-05-2020 17:35:12 ]DEBUG: test message