Created
March 26, 2015 09:22
-
-
Save brunal/01c89147a4e4239c818e to your computer and use it in GitHub Desktop.
Calling GIO with ctypes
This file contains hidden or 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
import ctypes | |
import ctypes.util | |
class GioURI(object): | |
"""Use gio URI function g_file_get_uri. Paths must be utf-8 encoded. | |
""" | |
name = "GIO" | |
def __init__(self): | |
self.libgio = self.get_library() | |
self.available = bool(self.libgio) | |
def get_library(self): | |
lib_name = ctypes.util.find_library("gio-2") | |
try: | |
return ctypes.cdll.LoadLibrary(lib_name) | |
except OSError: | |
return False | |
def uri(self, path): | |
print(b"getting g_file_ptr for %s" % path) | |
g_file_ptr = self.libgio.g_file_new_for_path(path) | |
if not g_file_ptr: | |
raise RuntimeError("No gfile pointer received for {0!r}".format( | |
path)) | |
try: | |
print("getting uri_ptr with %s" % g_file_ptr) | |
uri_ptr = self.libgio.g_file_get_uri(g_file_ptr) | |
except: | |
print("got exception") | |
raise | |
finally: | |
print("free g_file_ptr") | |
self.libgio.g_object_unref(g_file_ptr) | |
if not uri_ptr: | |
print("free uri_ptr") | |
self.libgio.g_free(uri_ptr) | |
raise RuntimeError("No URI received from the gfile pointer for " | |
"{0!r}".format(path)) | |
try: | |
print("getting uri") | |
uri = ctypes.c_char_p(uri_ptr).value | |
except: | |
print("got exception") | |
raise | |
finally: | |
print("free uri_ptr") | |
self.libgio.g_free(uri_ptr) | |
return uri | |
def test(): | |
gio = GioURI() | |
if not gio.available: | |
print("no gio") | |
return | |
# this will crash at some point... | |
for i in range(25): | |
print("Step %s" % i) | |
gio.uri(b"/foo/bar") | |
if __name__ == '__main__': | |
test() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment