3

这是学校的事情。

这是问题所在:

我们正在开发一个炸弹人克隆,我们必须实现一个脚本界面,允许用户制作自己的“人工智能”。我们选择使用 Perl。现在,我像这样构建 perl 模块:

以下是文件(测试目的):

SaibApi.xs:

#ifdef  __cplusplus
extern "C" {
#endif
#include "EXTERN.h"
#include "perl.h"
#include "XSUB.h"
#ifdef  __cplusplus
}
#endif
#include "ppport.h"
#include "SaibApi.hpp"

MODULE = SaibApi                PACKAGE = SaibApi

SaibApi *
SaibApi::new()

void
SaibApi::DESTROY()

void
SaibApi::PrintLol()

void
SaibApi::PrintPvar()

void
SaibApi::setLol(int arg)

SaibApi.hpp

#ifndef         SAIBAPI_HPP_
# define        SAIBAPI_HPP_

#include <iostream>

class           SaibApi {
public:
 SaibApi() {}
 ~SaibApi() {}
 void          PrintLol() { std::cout << "lol\n"; }
 void          PrintPvar() { std::cout << _lol << "\n"; }
 void          setLol(int arg) {_lol = arg;}
private:
 int           _lol;
};

#endif          /* !SAIBAPI_HPP_ */

Makefike.PL:

use 5.014002;
use ExtUtils::MakeMaker;

my $CC =                'g++';

# See lib/ExtUtils/MakeMaker.pm for details of how to influence
# the contents of the Makefile that is written.
WriteMakefile(
 NAME              => 'SaibApi',
 VERSION_FROM      => 'lib/SaibApi.pm', # finds $VERSION  
 PREREQ_PM         => {}, # e.g., Module::Name => 1.1
 ($] >= 5.005 ?     ## Add these new keywords supported since 5.005
 (ABSTRACT_FROM  => 'lib/SaibApi.pm', # retrieve abstract from module 
  AUTHOR         => 'Arkeopix <arkeopix@>') : ()),
 LIBS              => [''], # e.g., '-lm' 
 DEFINE            => '', # e.g., '-DHAVE_SOMETHING'
 INC               => '-I.', # e.g., '-I. -I/usr/include/other'
       # Un-comment this if you add C files to link with later:   
       # OBJECT            => '$(O_FILES)', # link all the C files too 
 CC                => $CC,
 LD                => '$(CC)',
 XSOPT             => '-C++',
 TYPEMAPS          => ['perlobject.map'],
);

为清楚起见,我排除了类型映射文件。

该模块已正确构建,我能够在 perl 中实例化 SaibApi 类。现在我们的问题是,显然没有办法同时在 c++ 和 perl 中实例化该类。我们试图做的是给用户一个简单的 API,允许通过简单的方法从我们的 C++ 代码中获取对象(很多 std::list 包含地图、玩家等......)。

例如:

#! /usr/bin/perl -w
#use SaibApi;

my $ai = new SaibApi();
my @map = ai->GetMap();
# some more code here...

我们做了很多研究,但是关于 XS 的文档有点稀缺。我们现在被困住了。如何同时在 c++ 和 perl 中实例化类,允许_lol在 c++ 部分中设置并在 perl 部分中打印它而无需使用该SetLol()方法?如果不可能,还有什么选择?

4

2 回答 2

1

我建议使用ExtUtils::XSppModule::Build::WithXSpp。它们使与 C++ 的接口变得更加容易。

于 2014-05-28T08:05:07.103 回答
0

最后我们决定使用共享内存,因为截止日期真的很快。

首先,我们创建内存段shmget(),共享我们的数据,shmat()然后将列表的内容推送到脚本堆栈中XPUSHs()

也许这不是最漂亮的方法,但它工作得很好。

于 2014-05-30T12:56:48.210 回答