Created
April 23, 2019 13:10
-
-
Save alphaKAI/b791c9326ac5c7561d4fdca8d3832960 to your computer and use it in GitHub Desktop.
Python3 Embedded into D. compile: $ dmd py3d.d -L-L/Path/To/Python3LibDirectory -L-lpython3.7m
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
/* | |
Python3 Embedded into D. | |
compile: $ dmd py3d.d -L-L/Path/To/Python3LibDirectory -L-lpython3.7m | |
Example... | |
dmd py3d.d -L-L/usr/local/opt/python/Frameworks/Python.framework/Versions/3.7/lib/python3.7/config-3.7m-darwin -L-lpython3.7m | |
*/ | |
import std.stdio, | |
std.string; | |
extern (C) { | |
void Py_SetProgramName(const char*); | |
void Py_Initialize(); | |
void PyRun_SimpleString(const char*); | |
int Py_FinalizeEx(); | |
} | |
static this() { | |
Py_SetProgramName("py3d".toStringz); /* optional but recommended */ | |
Py_Initialize(); | |
} | |
static ~this() { | |
if (Py_FinalizeEx() < 0) { throw new Error("Some Error"); } | |
} | |
void python(string py_code)() { | |
if (py_code.length == 0) return; | |
// 1行目のインデント幅をベースのインデントとして以後無視するようにする. | |
size_t base_indent_size; | |
string[] splitted = py_code.split("\n"); | |
foreach (line; splitted) { | |
if (!line.chomp.length) continue; | |
foreach (c; line) { | |
if (c == ' ' || c == '\t') { base_indent_size++; } | |
else { break; } | |
} | |
break; | |
} | |
// 実際に削る(インデントされてるものと仮定する) | |
if (base_indent_size) { | |
foreach (ref line; splitted) { | |
if (!line.chomp.length || !(base_indent_size < line.length)) continue; | |
line = line[base_indent_size..$]; | |
} | |
} | |
PyRun_SimpleString(splitted.join("\n").toStringz); | |
} | |
void main() { | |
python!q{ | |
print("Hello, python world! This is invoked by D"); | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment