Skip to content

Instantly share code, notes, and snippets.

@yorickpeterse
Last active August 29, 2015 14:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yorickpeterse/e06b31f964801fab2812 to your computer and use it in GitHub Desktop.
Save yorickpeterse/e06b31f964801fab2812 to your computer and use it in GitHub Desktop.
PG 18+
require 'ffi'
module Puby
module Python
extend FFI::Library
ffi_lib ['python2.7']
SINGLE_INPUT = 256
FILE_INPUT = 257
EVAL_INPUT = 258
attach_function :initialize, :Py_Initialize, [], :void
attach_function :finalize, :Py_Finalize, [], :void
attach_function :run_simple_string, :PyRun_SimpleString, [:string], :void
attach_function :python_string_from_string,
:PyString_FromString,
[:string],
:pointer
attach_function :python_string_as_string,
:PyString_AsString,
[:pointer],
:string
attach_function :run_string,
:PyRun_String,
[:string, :int, :pointer, :pointer],
:pointer
attach_function :run_file,
:PyRun_File,
[:pointer, :string, :int, :pointer, :pointer],
:pointer
attach_function :import_add_module,
:PyImport_AddModule,
[:string],
:pointer
attach_function :module_get_dict,
:PyModule_GetDict,
[:pointer],
:pointer
attach_function :object_get_attr_string,
:PyObject_GetAttrString,
[:pointer, :string],
:pointer
attach_function :object_call_object,
:PyObject_CallObject,
[:pointer, :pointer],
:pointer
attach_function :tuple_new, :PyTuple_New, [:int], :pointer
attach_function :increment_ref, :Py_IncRef, [:pointer], :void
attach_function :decrement_ref, :Py_DecRef, [:pointer], :void
end # Python
end # Puby
Puby::Python.initialize
main_module = Puby::Python.import_add_module('__main__')
main_dict = Puby::Python.module_get_dict(main_module)
code = <<-EOF
def testing():
return "Hello"
EOF
result = Puby::Python.run_string(code, Puby::Python::FILE_INPUT, main_dict, main_dict)
Puby::Python.decrement_ref(result)
method = Puby::Python.object_get_attr_string(main_module, "testing")
args = Puby::Python.tuple_new(0)
retval = Puby::Python.object_call_object(method, args)
string = Puby::Python.python_string_as_string(retval)
puts string
Puby::Python.decrement_ref(args)
Puby::Python.decrement_ref(retval)
Puby::Python.decrement_ref(method)
Puby::Python.decrement_ref(main_dict)
Puby::Python.finalize
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment