Skip to content

Commit

Permalink
ffi improvements
Browse files Browse the repository at this point in the history
  • Loading branch information
PsichiX committed Mar 28, 2019
1 parent ba37ff7 commit 6ea6e73
Show file tree
Hide file tree
Showing 9 changed files with 136 additions and 7 deletions.
1 change: 1 addition & 0 deletions .gitignore
@@ -1,5 +1,6 @@
/dist
/target
/unity
**/*.rs.bk
Cargo.lock
/*.sh
Expand Down
2 changes: 2 additions & 0 deletions Cargo.toml
Expand Up @@ -14,6 +14,7 @@ exclude = [
"cpp/**",
"dotnet/**",
"dist/**",
"unity/**",
]

[dependencies]
Expand All @@ -39,4 +40,5 @@ exclude = [
"cpp",
"dotnet",
"dist",
"unity",
]
37 changes: 36 additions & 1 deletion Makefile.toml
@@ -1,7 +1,7 @@
[tasks.all]
dependencies = [
"toolset",
"demos",
# "demos",
]

[tasks.toolset]
Expand All @@ -12,6 +12,7 @@ dependencies = [
"build-capi",
"build-dotnet-wrapper",
"toolset-post-produce",
# "unity-package",
"archive-toolset",
]

Expand Down Expand Up @@ -162,6 +163,40 @@ script = [
'''
]

# [tasks.unity-package]
# dependencies = [
# "update-unity-dependencies",
# "build-unity-package",
# ]
#
# [tasks.update-unity-dependencies]
# script = [
# '''
# echo "* update unity dependencies"
# cp -f target/release/psyche_capi.so unity/Psyche.Unity/Assets/Psyche/Plugins/psyche_capi.so
# cp -f dotnet/Psyche.NET/bin/Release/netstandard2.0/Psyche.NET.dll unity/Psyche.Unity/Assets/Psyche/Plugins/Psyche.NET.dll
# '''
# ]
#
# [tasks.update-unity-dependencies.windows]
# script = [
# '''
# echo "* update unity dependencies"
# copy "%CD%"\target\release\psyche_capi.dll "%CD%"\unity\Psyche.Unity\Assets\Psyche\Plugins\psyche_capi.dll
# copy "%CD%"\dotnet\Psyche.NET\bin\Release\netstandard2.0\Psyche.NET.dll "%CD%"\unity\Psyche.Unity\Assets\Psyche\Plugins\Psyche.NET.dll
# '''
# ]
#
# [tasks.build-unity-package]
# script = [
# '''$UNITY_BIN -projectPath "unity/Psyche.Unity/" -quit -batchmode -exportPackage Assets/Psyche ../../dist/toolset/psyche.unitypackage'''
# ]
#
# [tasks.build-unity-package.windows]
# script = [
# '''%UNITY_BIN% -projectPath "%CD%\unity\Psyche.Unity\" -quit -batchmode -exportPackage Assets\Psyche ..\..\dist\toolset\psyche.unitypackage'''
# ]

[tasks.demos]
dependencies = [
"build-demos",
Expand Down
6 changes: 6 additions & 0 deletions cpp/TestToolset/TestToolset.cpp
Expand Up @@ -15,6 +15,10 @@ void onGetYaml(void * context, const char* content) {
result->assign(content);
}

void onPrint(void * context, const char* content) {
std::cout << content << std::endl;
}

int main() {
BrainBuilderConfig brainConfig;
psyche_default_brain_builder_config(&brainConfig);
Expand All @@ -33,6 +37,8 @@ int main() {
brainConfig.sensors = 50;
brainConfig.effectors = 25;

psyche_brain_builder_to_string(&brainConfig, onPrint, nullptr);

auto brain = psyche_build_brain(&brainConfig);
std::vector<UID> sensors;
std::vector<UID> effectors;
Expand Down
11 changes: 8 additions & 3 deletions cpp/TestToolset/TestToolset.vcxproj
Expand Up @@ -111,7 +111,7 @@
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<AdditionalDependencies>kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;..\..\dist\toolset\lib\debug\psyche_capi.dll.lib;%(AdditionalDependencies)</AdditionalDependencies>
<AdditionalDependencies>..\..\dist\toolset\lib\debug\psyche_capi.dll.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
Expand Down Expand Up @@ -144,12 +144,14 @@
<PreprocessorDefinitions>NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<PrecompiledHeaderFile>pch.h</PrecompiledHeaderFile>
<AdditionalIncludeDirectories>..\..\dist\toolset\include</AdditionalIncludeDirectories>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
<AdditionalDependencies>..\..\dist\toolset\lib\release\psyche_capi.dll.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
Expand All @@ -168,8 +170,11 @@
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
<ItemGroup>
<Content Include="..\..\target\debug\psyche_capi.dll">
<Content Include="..\..\target\debug\psyche_capi.dll" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<Content Include="..\..\target\release\psyche_capi.dll" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
</ItemGroup>
</Project>
</Project>
29 changes: 27 additions & 2 deletions dotnet/Psyche.NET/NAPI.cs
Expand Up @@ -30,6 +30,7 @@ UIntPtr count
);

[StructLayout(LayoutKind.Sequential)]
[Serializable]
public struct UID
{
private readonly byte field0;
Expand All @@ -51,6 +52,7 @@ public struct UID
}

[StructLayout(LayoutKind.Sequential)]
[Serializable]
public struct Opt<T> where T : struct
{
public bool HasValue => hasValue;
Expand Down Expand Up @@ -78,6 +80,7 @@ public static Opt<T> None()
}

[StructLayout(LayoutKind.Sequential)]
[Serializable]
public struct BrainBuilderConfig
{
public double PropagationSpeed;
Expand All @@ -104,6 +107,7 @@ public struct BrainBuilderConfig
}

[StructLayout(LayoutKind.Sequential)]
[Serializable]
public struct OffspringBuilderConfig
{
public UIntPtr NewNeurons;
Expand All @@ -118,6 +122,7 @@ public struct OffspringBuilderConfig
}

[StructLayout(LayoutKind.Sequential)]
[Serializable]
public struct BrainActivityStats
{
public UIntPtr NeuronsCount;
Expand All @@ -140,11 +145,31 @@ public struct BrainActivityStats
public double SynapsesReceptorsMax;
}

[DllImport(LibName, CallingConvention = LibCall, EntryPoint = "psyche_brain_builder_to_string", CharSet = CharSet.Ansi)]
public extern static void BrainBuilderToString(
ref BrainBuilderConfig config,
[MarshalAs(UnmanagedType.FunctionPtr)]
OnResultString result,
IntPtr resultContext
);

[DllImport(LibName, CallingConvention = LibCall, EntryPoint = "psyche_offspring_builder_to_string", CharSet = CharSet.Ansi)]
public extern static void OffspringBuilderToString(
ref OffspringBuilderConfig config,
[MarshalAs(UnmanagedType.FunctionPtr)]
OnResultString result,
IntPtr resultContext
);

[DllImport(LibName, CallingConvention = LibCall, EntryPoint = "psyche_default_brain_builder_config", CharSet = CharSet.Ansi)]
public extern static void DefaultBrainBuilderConfig(ref BrainBuilderConfig config);
public extern static void DefaultBrainBuilderConfig(
ref BrainBuilderConfig config
);

[DllImport(LibName, CallingConvention = LibCall, EntryPoint = "psyche_default_offspring_builder_config", CharSet = CharSet.Ansi)]
public extern static void DefaultOffspringBuilderConfig(ref OffspringBuilderConfig config);
public extern static void DefaultOffspringBuilderConfig(
ref OffspringBuilderConfig config
);

[DllImport(LibName, CallingConvention = LibCall, EntryPoint = "psyche_build_brain", CharSet = CharSet.Ansi)]
public extern static UIntPtr BuildBrain(
Expand Down
1 change: 1 addition & 0 deletions dotnet/Psyche.NET/Psyche.NET.csproj
Expand Up @@ -7,6 +7,7 @@
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<PlatformTarget>x64</PlatformTarget>
<WarningLevel>1</WarningLevel>
</PropertyGroup>

<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">
Expand Down
9 changes: 8 additions & 1 deletion dotnet/Test/Program.cs
Expand Up @@ -8,7 +8,12 @@ class Program
{
static void Main(string[] args)
{
File.Copy("../../../../target/debug/psyche_capi.dll", "psyche_capi.dll", true);
Console.WriteLine(Environment.CurrentDirectory);
#if DEBUG
File.Copy("../../../../target/debug/psyche_capi.dll", "./psyche_capi.dll", true);
#else
File.Copy("../../../../target/release/psyche_capi.dll", "./psyche_capi.dll", true);
#endif

var brainConfig = new NAPI.BrainBuilderConfig();
NAPI.DefaultBrainBuilderConfig(ref brainConfig);
Expand All @@ -25,6 +30,8 @@ static void Main(string[] args)
brainConfig.Sensors = (UIntPtr)50;
brainConfig.Effectors = (UIntPtr)25;

NAPI.BrainBuilderToString(ref brainConfig, (context, content) => Console.WriteLine(content), IntPtr.Zero);

var brain = new Brain(ref brainConfig);
var sensors = brain.GetSensors();
var effectors = brain.GetEffectors();
Expand Down
47 changes: 47 additions & 0 deletions psyche-capi/src/lib.rs
Expand Up @@ -38,6 +38,7 @@ impl UID {
}

#[repr(C)]
#[derive(Debug)]
pub struct Opt<T> {
pub has_value: bool,
pub value: T,
Expand Down Expand Up @@ -80,6 +81,7 @@ impl<T> Opt<T> {
}

#[repr(C)]
#[derive(Debug)]
pub struct BrainBuilderConfig {
pub propagation_speed: Scalar,
pub neuron_potential_decay: Scalar,
Expand Down Expand Up @@ -160,6 +162,7 @@ impl Default for BrainBuilderConfig {
}

#[repr(C)]
#[derive(Debug)]
pub struct OffspringBuilderConfig {
pub new_neurons: usize,
pub new_connections: usize,
Expand Down Expand Up @@ -202,6 +205,7 @@ impl Default for OffspringBuilderConfig {
}

#[repr(C)]
#[derive(Debug)]
pub struct BrainActivityStats {
pub neurons_count: usize,
pub synapses_count: usize,
Expand Down Expand Up @@ -248,6 +252,34 @@ impl Into<BrainActivityStats> for PsycheBrainActivityStats {
}
}

#[no_mangle]
pub unsafe extern "C" fn psyche_brain_builder_to_string(
config: *const BrainBuilderConfig,
result: fn(*mut libc::c_void, *const libc::c_char),
result_context: *mut libc::c_void,
) {
if config.is_null() || (result as *const libc::c_void).is_null() {
result(null_mut(), null());
} else {
let content = CString::new(format!("{:#?}", *config)).unwrap();
result(result_context, content.as_ptr());
}
}

#[no_mangle]
pub unsafe extern "C" fn psyche_offspring_builder_to_string(
config: *const OffspringBuilderConfig,
result: fn(*mut libc::c_void, *const libc::c_char),
result_context: *mut libc::c_void,
) {
if config.is_null() || (result as *const libc::c_void).is_null() {
result(null_mut(), null());
} else {
let content = CString::new(format!("{:#?}", *config)).unwrap();
result(result_context, content.as_ptr());
}
}

#[no_mangle]
pub unsafe extern "C" fn psyche_default_brain_builder_config(config: *mut BrainBuilderConfig) {
if !config.is_null() {
Expand Down Expand Up @@ -313,6 +345,9 @@ pub extern "C" fn psyche_serialize_bytes_brain(
result: fn(*mut libc::c_void, *const libc::c_uchar, usize),
result_context: *mut libc::c_void,
) -> bool {
if (result as *const libc::c_void).is_null() {
return false;
}
if let Some(brain) = BRAINS.lock().unwrap().get(&handle) {
if let Ok(bytes) = brain_to_bytes(brain) {
result(result_context, bytes.as_ptr(), bytes.len());
Expand All @@ -330,6 +365,9 @@ pub extern "C" fn psyche_serialize_json_brain(
result: fn(*mut libc::c_void, *const libc::c_char),
result_context: *mut libc::c_void,
) -> bool {
if (result as *const libc::c_void).is_null() {
return false;
}
if let Some(brain) = BRAINS.lock().unwrap().get(&handle) {
if let Ok(json) = brain_to_json(brain, pretty) {
let json = CString::new(json).unwrap();
Expand All @@ -347,6 +385,9 @@ pub extern "C" fn psyche_serialize_yaml_brain(
result: fn(*mut libc::c_void, *const libc::c_char),
result_context: *mut libc::c_void,
) -> bool {
if (result as *const libc::c_void).is_null() {
return false;
}
if let Some(brain) = BRAINS.lock().unwrap().get(&handle) {
if let Ok(yaml) = brain_to_yaml(brain) {
let yaml = CString::new(yaml).unwrap();
Expand Down Expand Up @@ -434,6 +475,9 @@ pub extern "C" fn psyche_brain_get_sensors(
result: fn(*mut libc::c_void, *const UID, usize),
result_context: *mut libc::c_void,
) -> bool {
if (result as *const libc::c_void).is_null() {
return false;
}
if let Some(brain) = BRAINS.lock().unwrap().get(&handle) {
let uids = brain
.get_sensors()
Expand All @@ -453,6 +497,9 @@ pub extern "C" fn psyche_brain_get_effectors(
result: fn(*mut libc::c_void, *const UID, usize),
result_context: *mut libc::c_void,
) -> bool {
if (result as *const libc::c_void).is_null() {
return false;
}
if let Some(brain) = BRAINS.lock().unwrap().get(&handle) {
let uids = brain
.get_effectors()
Expand Down

0 comments on commit 6ea6e73

Please sign in to comment.