1
0
Fork 0
mirror of https://github.com/ruby/ruby.git synced 2022-11-09 12:17:21 -05:00

Add a sample which shows how to deal with C++ libraries.

git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@2394 b2dd03c8-39d4-4d8f-98ff-823fe69b080e
This commit is contained in:
ttate 2002-04-20 16:09:44 +00:00
parent 9a8bcafe55
commit 73331b45e0
3 changed files with 97 additions and 0 deletions

View file

@ -17,6 +17,8 @@ mkcall.rb
mkcallback.rb
mkcbtable.rb
ptr.c
sample/c++sample.C
sample/c++sample.rb
sample/drives.rb
sample/getch.rb
sample/libc.rb

35
ext/dl/sample/c++sample.C Normal file
View file

@ -0,0 +1,35 @@
#include <stdio.h>
class Person {
private:
const char *name;
int age;
public:
Person(const char *name, int age);
const char * get_name();
int get_age();
void set_age(int i);
};
Person::Person(const char *name, int age)
: name(name), age(age)
{
/* empty */
}
const char *
Person::get_name()
{
return name;
}
int
Person::get_age(){
return age;
}
void
Person::set_age(int i){
age = i;
}

View file

@ -0,0 +1,60 @@
=begin
This script shows how to deal with C++ classes using Ruby/DL.
You must build a dynamic loadable library using "c++sample.C"
to run this script as follows:
$ g++ -o libsample.so -shared c++sample.C
=end
require 'dl'
require 'dl/import'
require 'dl/struct'
# Give a name of dynamic loadable library
LIBNAME = ARGV[0] || "libsample.so"
class Person
module Core
extend DL::Importable
dlload LIBNAME
# mangled symbol names
extern "void __6PersonPCci(void *, const char *, int)"
extern "const char *get_name__6Person(void *)"
extern "int get_age__6Person(void *)"
extern "void set_age__6Personi(void *, int)"
Data = struct [
"char *name",
"int age",
]
end
def initialize(name, age)
@ptr = Core::Data.alloc
Core::__6PersonPCci(@ptr, name, age)
end
def get_name()
str = Core::get_name__6Person(@ptr)
if( str )
str.to_s
else
nil
end
end
def get_age()
Core::get_age__6Person(@ptr)
end
def set_age(age)
Core::set_age__6Personi(@ptr, age)
end
end
obj = Person.new("ttate", 1)
p obj.get_name()
p obj.get_age()
obj.set_age(10)
p obj.get_age()