summaryrefslogtreecommitdiff
path: root/ext
diff options
context:
space:
mode:
authorttate <ttate@b2dd03c8-39d4-4d8f-98ff-823fe69b080e>2002-04-20 16:09:44 +0000
committerttate <ttate@b2dd03c8-39d4-4d8f-98ff-823fe69b080e>2002-04-20 16:09:44 +0000
commit73331b45e0f81df08f9af6bf229d8a09aec1ff5f (patch)
treec25c28f4ceddb3a9639407546ae6faa9d77b80ca /ext
parent9a8bcafe554449f9de5f7b0690434a81721f3ec8 (diff)
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
Diffstat (limited to 'ext')
-rw-r--r--ext/dl/MANIFEST2
-rw-r--r--ext/dl/sample/c++sample.C35
-rw-r--r--ext/dl/sample/c++sample.rb60
3 files changed, 97 insertions, 0 deletions
diff --git a/ext/dl/MANIFEST b/ext/dl/MANIFEST
index c5cd5839a8..261b4ad914 100644
--- a/ext/dl/MANIFEST
+++ b/ext/dl/MANIFEST
@@ -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
diff --git a/ext/dl/sample/c++sample.C b/ext/dl/sample/c++sample.C
new file mode 100644
index 0000000000..d083d337a7
--- /dev/null
+++ b/ext/dl/sample/c++sample.C
@@ -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;
+}
diff --git a/ext/dl/sample/c++sample.rb b/ext/dl/sample/c++sample.rb
new file mode 100644
index 0000000000..29887df845
--- /dev/null
+++ b/ext/dl/sample/c++sample.rb
@@ -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()