Created
August 10, 2022 10:14
-
-
Save eregon/8ac387dc77b03d08f2259a64b9361934 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'tmpdir' | |
require 'rbconfig' | |
def inline_c_extension(c_code) | |
Dir.mktmpdir('inline_c_extension') do |dir| | |
File.write("#{dir}/cext.c", c_code) | |
File.write("#{dir}/extconf.rb", <<~RUBY) | |
require 'mkmf' | |
create_makefile('cext') | |
RUBY | |
out = IO.popen([RbConfig.ruby, 'extconf.rb'], chdir: dir, &:read) | |
raise "ruby extconf.rb failed: #{$?.inspect}\n#{out}" unless $?.success? | |
out = IO.popen(['make'], chdir: dir, &:read) | |
raise "make failed: #{$?.inspect}\n#{out}" unless $?.success? | |
require "#{dir}/cext.#{RbConfig::CONFIG['DLEXT']}" | |
end | |
end | |
inline_c_extension <<~C | |
#include "ruby.h" | |
#include "ruby/encoding.h" | |
static VALUE foo(VALUE self) { | |
return INT2FIX(rb_define_dummy_encoding("foo")); | |
} | |
void Init_cext(void) { | |
VALUE c = rb_define_class("Foo", rb_cObject); | |
rb_define_singleton_method(c, "foo", foo, 0); | |
} | |
C | |
p Foo.foo | |
p enc=Encoding.find("foo") | |
p Encoding.find("foo").ascii_compatible? | |
p "abc".force_encoding(enc).encode("UTF-8") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment