├── .gitignore ├── CITATION.cff ├── LICENSE ├── README.md ├── com.python-unity-shared-memory ├── README.md ├── README.md.meta ├── Runtime.meta ├── Runtime │ ├── Core.cs │ ├── Core.cs.meta │ ├── PythonUnitySharedMemory.asmdef │ └── PythonUnitySharedMemory.asmdef.meta ├── Tests.meta ├── Tests │ ├── Editor.meta │ └── Editor │ │ ├── PythonUnitySharedMemory.EditorTests.asmdef │ │ ├── PythonUnitySharedMemory.EditorTests.asmdef.meta │ │ ├── Test_Integration.cs │ │ ├── Test_Integration.cs.meta │ │ ├── Test_SM.cs │ │ └── Test_SM.cs.meta ├── package.json └── package.json.meta └── python_unity_shared_memory ├── python_unity_shared_memory └── __init__.py ├── setup.py └── test ├── __init__.py ├── test_integration.py └── test_sm.py /.gitignore: -------------------------------------------------------------------------------- 1 | # This .gitignore file should be placed at the root of your Unity project directory 2 | # 3 | # Get latest from https://github.com/github/gitignore/blob/master/Unity.gitignore 4 | # 5 | /[Ll]ibrary/ 6 | /[Tt]emp/ 7 | /[Oo]bj/ 8 | /[Bb]uild/ 9 | /[Bb]uilds/ 10 | /[Ll]ogs/ 11 | /[Mm]emoryCaptures/ 12 | 13 | # Asset meta data should only be ignored when the corresponding asset is also ignored 14 | !/[Aa]ssets/**/*.meta 15 | 16 | # Uncomment this line if you wish to ignore the asset store tools plugin 17 | # /[Aa]ssets/AssetStoreTools* 18 | 19 | # Autogenerated Jetbrains Rider plugin 20 | [Aa]ssets/Plugins/Editor/JetBrains* 21 | 22 | # Visual Studio cache directory 23 | .vs/ 24 | 25 | # Gradle cache directory 26 | .gradle/ 27 | 28 | # Autogenerated VS/MD/Consulo solution and project files 29 | ExportedObj/ 30 | .consulo/ 31 | *.csproj 32 | *.unityproj 33 | *.sln 34 | *.suo 35 | *.tmp 36 | *.user 37 | *.userprefs 38 | *.pidb 39 | *.booproj 40 | *.svd 41 | *.pdb 42 | *.mdb 43 | *.opendb 44 | *.VC.db 45 | 46 | # Unity3D generated meta files 47 | *.pidb.meta 48 | *.pdb.meta 49 | *.mdb.meta 50 | 51 | # Unity3D generated file on crash reports 52 | sysinfo.txt 53 | 54 | # Builds 55 | *.apk 56 | *.unitypackage 57 | 58 | # Crashlytics generated file 59 | crashlytics-build.properties 60 | 61 | # Ignore virtualenv 62 | /virt/ 63 | 64 | # Ignore Python generated files 65 | __pycache__/ 66 | *.py[cod] 67 | 68 | # C extensions 69 | *.so 70 | 71 | # Distribution / packaging 72 | bin/ 73 | build/ 74 | develop-eggs/ 75 | dist/ 76 | eggs/ 77 | lib/ 78 | lib64/ 79 | parts/ 80 | sdist/ 81 | var/ 82 | *.egg-info/ 83 | .installed.cfg 84 | *.egg 85 | 86 | # Installer logs 87 | pip-log.txt 88 | pip-delete-this-directory.txt 89 | 90 | # Unit test / coverage reports 91 | .tox/ 92 | .coverage 93 | .cache 94 | nosetests.xml 95 | coverage.xml 96 | 97 | # Translations 98 | *.mo 99 | 100 | # Mr Developer 101 | .mr.developer.cfg 102 | .project 103 | .pydevproject 104 | 105 | # Rope 106 | .ropeproject 107 | 108 | # Django stuff: 109 | *.log 110 | *.pot 111 | 112 | # Sphinx documentation 113 | docs/_build/ 114 | -------------------------------------------------------------------------------- /CITATION.cff: -------------------------------------------------------------------------------- 1 | cff-version: 1.2.0 2 | message: "If you use this software, please cite it as below." 3 | authors: 4 | - family-names: Berges 5 | given-names: Vincent-Pierre 6 | orcid: https://orcid.org/0000-0002-7528-5560 7 | title: "PythonUnitySharedMemory" 8 | version: 0.1.0 9 | date-released: 2021-10-29 10 | url: "https://github.com/vincentpierre/PythonUnitySharedMemory" -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2021 Vincent-Pierre Berges 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # PythonUnitySharedMemory 2 | Using a shared file to exchange data between Unity and Python. 3 | 4 | ## Functionality 5 | - Can only exchange booleans, integers, floats, strings and byte arrays. 6 | - Easy to add new types. 7 | - Lightweight : Only one [script on C#](com.python-unity-shared-memory/Runtime/Core.cs) and one [script on Python](python_unity_shared_memory/python_unity_shared_memory/__init__.py) 8 | - Shared memory not work across machines like sockets would. 9 | - Shared memory has the potential to be extremely fast when the volume of data is large. 10 | 11 | ## Recommended Installation 12 | ### Unity 13 | Via the Package Manager. Add a dependency to the `manifest.json` of your project: 14 | ``` 15 | { 16 | "dependencies": { 17 | "com.python-unity-shared-memory": "https://github.com/vincentpierre/PythonUnitySharedMemory.git?path=/com.python-unity-shared-memory" 18 | } 19 | } 20 | ``` 21 | Alternatively, you can clone the repository locally and use you local path. 22 | 23 | ### Python 24 | Clone the repository and run the command 25 | ``` 26 | pip install -e python_unity_shared_memory 27 | ``` 28 | 29 | ## API 30 | The API is meant to be identical between C# and Python. 31 | 32 | ### Create a shared memory file 33 | 34 | #### Python 35 | 36 | ``` 37 | from python_unity_shared_memory import SharedMemory, delete_files 38 | 39 | sm = SharedMemory( 40 | prefix="my-file", # The ID of the shared memory 41 | capacity=100, # The number of bytes of the file 42 | create_new=False, # Wether to create the file or open it 43 | timeout=30) # How low to timeout (-1 means no timeout) 44 | ``` 45 | 46 | #### C# 47 | 48 | ``` 49 | using PythonUnitySharedMemory; 50 | 51 | var sm = new SharedMemory( 52 | prefix:"my-file", // The ID of the shared memory 53 | capacity:100, // The number of bytes of the file 54 | createNew:true, // Wether to create the file or open it 55 | timeout:30); // How low to timeout (-1 means no timeout) 56 | ``` 57 | 58 | #### Notes 59 | 60 | Note that : 61 | - In the example above, the id "my-file" need to be identical for the two shared memory partitions to communicate. 62 | - You can open as many shared memory files as you want. 63 | - The `capacity` must be the same on both sizes. 64 | - In this case, Unity creates the share memory and Python joins it (see `create_new`/`createNew` arguments) 65 | - `timeout` is expressed in seconds 66 | - A negative `timeout` means no timeout 67 | 68 | ### Resizing 69 | 70 | #### Python 71 | 72 | ``` 73 | sm.resize(new_capacity) 74 | ``` 75 | 76 | #### C# 77 | 78 | ``` 79 | sm.Resize(newCapacity) 80 | ``` 81 | 82 | #### Notes 83 | If your shared memory partition is too small, you can resize it. If you do, the new capacity must be strictly greater than the previous one. When resizing, a new file will be created and both SharedMemory objects will switch to using the new one. This operation is expensive, it is recommended to use it only when necessary and to allocate a greater capacity than needed. 84 | 85 | ### Read and write 86 | #### Python 87 | 88 | Available read methods take as argument an offset in the shared memory and return a tuple of (value, new_offset): 89 | - `read_bool` 90 | - `read_int32` 91 | - `read_float32` 92 | - `read_string` 93 | - `read_bytes` (takes as input an offset and a length argument) 94 | 95 | And the write methods take as argument an offset and a value. They will return the new offset. 96 | - `write_bool` 97 | - `write_int32` 98 | - `write_float32` 99 | - `write_string` 100 | - `write_bytes` 101 | 102 | For example: 103 | ``` 104 | new_offset = sm.write_string(offset, "my-string") 105 | my_string, new_offset = sm.read_string(offset) 106 | assert my_string == "my-string" 107 | ``` 108 | 109 | #### C# 110 | 111 | Available read methods take as argument an offset in the shared memory and return a tuple of (value, new_offset): 112 | - `ReadBool` 113 | - `ReadInt32` 114 | - `ReadFloat32` 115 | - `ReadString` 116 | - `ReadBytes` (takes as input an offset and a *length* argument) 117 | 118 | And the write methods take as argument an offset and a value. They will return the new offset. 119 | - `WriteBool` 120 | - `WriteInt32` 121 | - `WriteFloat32` 122 | - `WriteString` 123 | - `WriteBytes` 124 | 125 | For example: 126 | ``` 127 | newOffset = sm.WriteString(offset, "my-string") 128 | (str my_string, int new_offset) = sm.ReadString(offset) 129 | assert my_string == "my-string" 130 | ``` 131 | #### Notes 132 | The reason the read and write methods return the new offset is to make it easy to chain reads and writes: 133 | ``` 134 | offset = 0 135 | value_1, offset = sm.read_int32(offset) # offset is now 4 136 | value_2, offset = sm.read_float32(offset) # offset is now 8 137 | ``` 138 | 139 | Note also that C# tuples are accessed with the properties `tuple.Item1` and `tuple.Item2` while Python can access tuples like arrays `tuple[0]` and `tuple[1]` 140 | 141 | ### Synchronicity 142 | The `give_control()` and `GiveControl()` methods will signal the other process that it is their turn to edit the file. Until the other process gives control back, the current process will be waiting. 143 | It is possible to pass an optional argument `wait=False` to `give_control` on both Python and C#. In this case the control will be passed to the other process but the current process will not be blocked. You can manually block the process until control is given back with `wait_unblocked`/`WaitUnblocked`. Note that if you give back control without waiting *and* edit the shared memory before calling `wait_unblocked` you expose yourself to *race conditions*. 144 | 145 | ### Terminating 146 | You can call the `close()`/`Close()` methods to signal the file is no longer being used and call `delete()/Delete()` to delete it. If you want to manually delete your old shared memory files, you can call the method `delete_files(prefix)` on Python and `SharedMemory.DeleteFiles(prefix)` on C#. -------------------------------------------------------------------------------- /com.python-unity-shared-memory/README.md: -------------------------------------------------------------------------------- 1 | [Documentation](../README.md) -------------------------------------------------------------------------------- /com.python-unity-shared-memory/README.md.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: e7a73fa930c0b4d518e61e4147e53ced 3 | TextScriptImporter: 4 | externalObjects: {} 5 | userData: 6 | assetBundleName: 7 | assetBundleVariant: 8 | -------------------------------------------------------------------------------- /com.python-unity-shared-memory/Runtime.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: af24a41c1055b44829bbc171e4ede054 3 | folderAsset: yes 4 | DefaultImporter: 5 | externalObjects: {} 6 | userData: 7 | assetBundleName: 8 | assetBundleVariant: 9 | -------------------------------------------------------------------------------- /com.python-unity-shared-memory/Runtime/Core.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.IO; 3 | using System.IO.MemoryMappedFiles; 4 | using System.Text; 5 | 6 | namespace PythonUnitySharedMemory 7 | { 8 | unsafe internal class Core 9 | { 10 | internal const string k_Dir= "python_unity_shared_memory"; 11 | public MemoryMappedViewAccessor Mem; 12 | public string FilePath; 13 | 14 | public Core(string name, int capacity, bool createNew) 15 | { 16 | if (name.Length < 1){ 17 | throw new ArgumentException("Name must be more than one character long"); 18 | } 19 | var directory = Path.Combine(Path.GetTempPath(), k_Dir); 20 | if (!Directory.Exists(directory)) 21 | { 22 | Directory.CreateDirectory(directory); 23 | } 24 | FilePath = Path.Combine(directory, name); 25 | if (createNew) 26 | { 27 | if (File.Exists(FilePath)) 28 | { 29 | throw new IOException($"The file {name} already exists"); 30 | } 31 | using (var fs = new FileStream(FilePath, FileMode.Create, FileAccess.Write)) 32 | { 33 | // Clear existing data 34 | fs.Write(new byte[capacity], 0, capacity); 35 | } 36 | } 37 | long length = new System.IO.FileInfo(FilePath).Length; 38 | var mmf = MemoryMappedFile.CreateFromFile( 39 | File.Open(FilePath, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite), 40 | null, 41 | length, 42 | MemoryMappedFileAccess.ReadWrite, 43 | HandleInheritability.None, 44 | false 45 | ); 46 | Mem = mmf.CreateViewAccessor(0, length, MemoryMappedFileAccess.ReadWrite); 47 | mmf.Dispose(); 48 | } 49 | 50 | public void Close() 51 | { 52 | if (Opened) 53 | { 54 | Mem.SafeMemoryMappedViewHandle.ReleasePointer(); 55 | Mem.Dispose(); 56 | } 57 | } 58 | 59 | protected bool Opened 60 | { 61 | get 62 | { 63 | return Mem.CanWrite; 64 | } 65 | } 66 | 67 | public void Delete() 68 | { 69 | Close(); 70 | File.Delete(FilePath); 71 | } 72 | 73 | 74 | public (int,int) ReadInt32(int offset) 75 | { 76 | var val = Mem.ReadInt32(offset); 77 | return (val, offset + 4); 78 | } 79 | public (bool, int) ReadBool(int offset) 80 | { 81 | var val = Mem.ReadBoolean(offset); 82 | return (val, offset + 1); 83 | } 84 | public (byte[], int) ReadBytes(int offset, int length){ 85 | var arr = new byte[length]; 86 | Mem.ReadArray(offset, arr, 0, length); 87 | return (arr, offset+length); 88 | } 89 | public int WriteInt32(int offset, int value) 90 | { 91 | Mem.Write(offset, value); 92 | return offset + 4; 93 | } 94 | public int WriteBool(int offset, bool value) 95 | { 96 | Mem.Write(offset, value); 97 | return offset + 1; 98 | } 99 | public int WriteBytes(int offset, byte[] data){ 100 | Mem.WriteArray(offset, data, 0, data.Length); 101 | return offset + data.Length; 102 | } 103 | 104 | } 105 | 106 | 107 | public class SharedMemory{ 108 | private const int k_Version = 1; 109 | private const int k_VersionOffset = 0; 110 | private const int k_FileNumberOffset=4; 111 | private const int k_CapacityOffset=8; 112 | private const int k_PythonActiveOffset=12; 113 | private const int k_UnityActiveOffset=13; 114 | private const int k_CloseOffset=14; 115 | private int m_LastFileNumber; 116 | 117 | private string m_Name; 118 | private float m_Timeout; 119 | private Core m_Hook; 120 | private Core m_Current; 121 | 122 | public static void DeleteFiles(string prefix){ 123 | var directory = Path.Combine(Path.GetTempPath(), Core.k_Dir); 124 | if (!Directory.Exists(directory)) 125 | { 126 | Directory.CreateDirectory(directory); 127 | } 128 | DirectoryInfo dir = new DirectoryInfo(directory); 129 | FileInfo[] files = dir.GetFiles(prefix + "*"); 130 | foreach(FileInfo f in files){ 131 | f.Delete(); 132 | } 133 | } 134 | 135 | public SharedMemory(string prefix, int capacity, bool createNew, float timeout){ 136 | m_Name = prefix; 137 | m_Timeout = timeout; 138 | if (m_Name[m_Name.Length - 1] == '_'){ 139 | throw new ArgumentException("The name cannot end with a _."); 140 | } 141 | m_Hook = new Core(m_Name, k_CloseOffset + 1, createNew); 142 | if(createNew){ 143 | Version = k_Version; 144 | FileNumber = 1; 145 | Capacity = capacity; 146 | m_Hook.WriteBool(k_UnityActiveOffset, true); 147 | } 148 | else{ 149 | if(Version != k_Version){ 150 | throw new Exception($"Incompatible Versions between Unity (v{k_Version}) and Python (v{Version})"); 151 | } 152 | } 153 | m_LastFileNumber = FileNumber; 154 | m_Current = new Core(m_Name + new string('_', FileNumber), Capacity, createNew); 155 | WaitUnblocked(); 156 | } 157 | 158 | public void Resize(int capacity){ 159 | FileNumber += 1; 160 | int oldCapacity = Capacity; 161 | if (capacity < oldCapacity){ 162 | throw new ArgumentException("New capacity must be larget than old capacity."); 163 | } 164 | Capacity = capacity; 165 | var newCurrent = new Core(m_Name + new string('_', FileNumber), Capacity, true); 166 | newCurrent.WriteBytes(0, m_Current.ReadBytes(0, oldCapacity).Item1); 167 | m_Current = newCurrent; 168 | m_LastFileNumber = FileNumber; 169 | } 170 | 171 | public void WaitUnblocked(){ 172 | if (Blocked){ 173 | var t0 = DateTime.Now.Ticks; 174 | int iteration = 0; 175 | while(Blocked && Active){ 176 | if (iteration % 1e8 == 0 && m_Timeout > 0){ 177 | if (DateTime.Now.Ticks - t0 > m_Timeout * 1e7){ 178 | Delete(); 179 | throw new TimeoutException("Communication took too long."); 180 | } 181 | } 182 | } 183 | } 184 | if (!Active){ 185 | Delete(); 186 | throw new Exception("Python has stopped."); 187 | } 188 | if(m_LastFileNumber != FileNumber){ 189 | m_LastFileNumber = FileNumber; 190 | m_Current.Delete(); 191 | m_Current = new Core(m_Name+ new string('_', FileNumber), Capacity, false); 192 | } 193 | } 194 | 195 | public void Close(){ 196 | m_Hook.WriteBool(k_CloseOffset,true); 197 | m_Hook.Close(); 198 | m_Current.Delete(); 199 | } 200 | public void Delete(){ 201 | Close(); 202 | m_Hook.Delete(); 203 | m_Current.Delete(); 204 | } 205 | 206 | public void Dispose(){ 207 | Delete(); 208 | } 209 | 210 | 211 | 212 | private int Version{ 213 | get{return m_Hook.ReadInt32(k_VersionOffset).Item1;} 214 | set{m_Hook.WriteInt32(k_VersionOffset, value);} 215 | } 216 | private int FileNumber{ 217 | get{return m_Hook.ReadInt32(k_FileNumberOffset).Item1;} 218 | set{m_Hook.WriteInt32(k_FileNumberOffset, value);} 219 | } 220 | private int Capacity{ 221 | get{return m_Hook.ReadInt32(k_CapacityOffset).Item1;} 222 | set{m_Hook.WriteInt32(k_CapacityOffset, value);} 223 | } 224 | private bool Active{ 225 | get{return !m_Hook.ReadBool(k_CloseOffset).Item1;} 226 | } 227 | 228 | public void UnsafeSignalPythonUnblocked(){ 229 | m_Hook.WriteBool(k_PythonActiveOffset, true); 230 | } 231 | public void UnsafeSignalUnityBlocked(){ 232 | m_Hook.WriteBool(k_UnityActiveOffset, false); 233 | } 234 | public void GiveControl(bool wait = true){ 235 | WaitUnblocked(); 236 | UnsafeSignalUnityBlocked(); 237 | UnsafeSignalPythonUnblocked(); 238 | if (wait){ 239 | WaitUnblocked(); 240 | } 241 | } 242 | public bool Blocked{ 243 | get{return !m_Hook.ReadBool(k_UnityActiveOffset).Item1;} 244 | } 245 | 246 | // The read methods 247 | public (int, int) ReadInt32(int offset){ 248 | WaitUnblocked(); 249 | return m_Current.ReadInt32(offset); 250 | } 251 | public (bool, int) ReadBool(int offset){ 252 | WaitUnblocked(); 253 | return m_Current.ReadBool(offset); 254 | } 255 | public (byte[], int) ReadBytes(int offset, int length){ 256 | WaitUnblocked(); 257 | return m_Current.ReadBytes(offset, length); 258 | } 259 | public (float, int) ReadFloat32(int offset){ 260 | WaitUnblocked(); 261 | return (m_Current.Mem.ReadSingle(offset), offset + 4); 262 | } 263 | public (string, int) ReadString(int offset){ 264 | WaitUnblocked(); 265 | (int length, _) = ReadInt32(offset); 266 | (var data, _) = ReadBytes(offset + 4, length); 267 | return (Encoding.ASCII.GetString(data), offset + 4 + length); 268 | 269 | } 270 | 271 | 272 | // The write methods 273 | public int WriteInt32(int offset, int value){ 274 | WaitUnblocked(); 275 | return m_Current.WriteInt32(offset, value); 276 | } 277 | public int WriteBool(int offset, bool value){ 278 | WaitUnblocked(); 279 | return m_Current.WriteBool(offset, value); 280 | } 281 | public int WriteBytes(int offset, byte[] data){ 282 | WaitUnblocked(); 283 | return m_Current.WriteBytes(offset, data); 284 | } 285 | public int WriteFloat32(int offset, float value){ 286 | WaitUnblocked(); 287 | m_Current.Mem.Write(offset, value); 288 | return offset + 4; 289 | } 290 | 291 | public int WriteString(int offset, string value){ 292 | WaitUnblocked(); 293 | var length = value.Length; 294 | offset = WriteInt32(offset, length); 295 | return WriteBytes(offset, Encoding.ASCII.GetBytes(value)); 296 | } 297 | 298 | } 299 | } -------------------------------------------------------------------------------- /com.python-unity-shared-memory/Runtime/Core.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 672f6fe52378548f3a0862d02b9aab43 3 | MonoImporter: 4 | externalObjects: {} 5 | serializedVersion: 2 6 | defaultReferences: [] 7 | executionOrder: 0 8 | icon: {instanceID: 0} 9 | userData: 10 | assetBundleName: 11 | assetBundleVariant: 12 | -------------------------------------------------------------------------------- /com.python-unity-shared-memory/Runtime/PythonUnitySharedMemory.asmdef: -------------------------------------------------------------------------------- 1 | { 2 | "name": "PythonUnitySharedMemory", 3 | "references": [ 4 | ], 5 | "includePlatforms": [], 6 | "excludePlatforms": [], 7 | "allowUnsafeCode": true, 8 | "overrideReferences": false, 9 | "precompiledReferences": [], 10 | "autoReferenced": true, 11 | "defineConstraints": [], 12 | "versionDefines": [], 13 | "noEngineReferences": false 14 | } 15 | -------------------------------------------------------------------------------- /com.python-unity-shared-memory/Runtime/PythonUnitySharedMemory.asmdef.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 982e560bc8f354ea3b53c9b7005b7a51 3 | AssemblyDefinitionImporter: 4 | externalObjects: {} 5 | userData: 6 | assetBundleName: 7 | assetBundleVariant: 8 | -------------------------------------------------------------------------------- /com.python-unity-shared-memory/Tests.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: c2f01d93e61a949299f8ff8d3f878070 3 | folderAsset: yes 4 | DefaultImporter: 5 | externalObjects: {} 6 | userData: 7 | assetBundleName: 8 | assetBundleVariant: 9 | -------------------------------------------------------------------------------- /com.python-unity-shared-memory/Tests/Editor.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: f27c27ed6fe814a2a81b6c46b67b23c6 3 | folderAsset: yes 4 | DefaultImporter: 5 | externalObjects: {} 6 | userData: 7 | assetBundleName: 8 | assetBundleVariant: 9 | -------------------------------------------------------------------------------- /com.python-unity-shared-memory/Tests/Editor/PythonUnitySharedMemory.EditorTests.asmdef: -------------------------------------------------------------------------------- 1 | { 2 | 3 | "name": "PythonUnitySharedMemory.Tests", 4 | "references": [ 5 | "PythonUnitySharedMemory" 6 | ], 7 | "optionalUnityReferences": [ 8 | "TestAssemblies" 9 | ], 10 | "includePlatforms": [ 11 | "Editor" 12 | ], 13 | "excludePlatforms": [], 14 | "allowUnsafeCode": false, 15 | "overrideReferences": false, 16 | "precompiledReferences": [], 17 | "autoReferenced": false, 18 | "defineConstraints": [], 19 | "versionDefines": [] 20 | } -------------------------------------------------------------------------------- /com.python-unity-shared-memory/Tests/Editor/PythonUnitySharedMemory.EditorTests.asmdef.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 371d213807e5a40c9b08821bfc698126 3 | AssemblyDefinitionImporter: 4 | externalObjects: {} 5 | userData: 6 | assetBundleName: 7 | assetBundleVariant: 8 | -------------------------------------------------------------------------------- /com.python-unity-shared-memory/Tests/Editor/Test_Integration.cs: -------------------------------------------------------------------------------- 1 | using NUnit.Framework; 2 | using UnityEngine; 3 | using System.IO; 4 | using PythonUnitySharedMemory; 5 | 6 | namespace PythonUnitySharedMemory.Tests.Editor{ 7 | 8 | public class TestSharedMemoryIntegration 9 | { 10 | 11 | [Test] 12 | public void TestIntegration() 13 | { 14 | SharedMemory.DeleteFiles("test"); 15 | Debug.Log("Launch the pytest command now, the test has started."); 16 | // 17 | var sm = new SharedMemory("test", 100, true, 30); 18 | sm.WriteString(42, "foo"); 19 | // 20 | sm.GiveControl(); //block p1 21 | // 22 | Assert.AreEqual("bar", sm.ReadString(42).Item1); 23 | sm.WriteString(42, "foo"); 24 | // 25 | sm.GiveControl(); // block p3 26 | 27 | // 28 | Assert.AreEqual("bar142", sm.ReadString(142).Item1); 29 | Assert.AreEqual("foo", sm.ReadString(42).Item1); 30 | 31 | 32 | sm.Resize(300); 33 | // 34 | sm.GiveControl(); // block p5> 35 | 36 | // 37 | Assert.AreEqual("bar342", sm.ReadString(342).Item1); 38 | sm.Dispose(); 39 | // 40 | } 41 | } 42 | } -------------------------------------------------------------------------------- /com.python-unity-shared-memory/Tests/Editor/Test_Integration.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 650c269b127c742f0931519e7d79bd24 3 | MonoImporter: 4 | externalObjects: {} 5 | serializedVersion: 2 6 | defaultReferences: [] 7 | executionOrder: 0 8 | icon: {instanceID: 0} 9 | userData: 10 | assetBundleName: 11 | assetBundleVariant: 12 | -------------------------------------------------------------------------------- /com.python-unity-shared-memory/Tests/Editor/Test_SM.cs: -------------------------------------------------------------------------------- 1 | using NUnit.Framework; 2 | using UnityEngine; 3 | using System.IO; 4 | using PythonUnitySharedMemory; 5 | 6 | namespace PythonUnitySharedMemory.Tests.Editor{ 7 | 8 | public class TestSharedMemory 9 | { 10 | 11 | [Test] 12 | public void TestCreate() 13 | { 14 | SharedMemory.DeleteFiles("test"); 15 | var sm = new SharedMemory("test", 100, true, 30); 16 | sm.Close(); 17 | 18 | var path = Path.Combine(Path.GetTempPath(), "python_unity_shared_memory/test"); 19 | Assert.True(File.Exists(path)); 20 | SharedMemory.DeleteFiles("test"); 21 | Assert.False(File.Exists(path)); 22 | } 23 | 24 | [Test] 25 | public void TestReadWrite(){ 26 | SharedMemory.DeleteFiles("test"); 27 | var sm = new SharedMemory("test", 100, true, 30); 28 | 29 | Assert.False(sm.ReadBool(0).Item1); 30 | sm.WriteBool(0, true); 31 | Assert.True(sm.ReadBool(0).Item1); 32 | 33 | Assert.AreEqual(sm.ReadInt32(3).Item1, 0); 34 | sm.WriteInt32(3, 42); 35 | Assert.AreEqual(sm.ReadInt32(3).Item1, 42); 36 | 37 | 38 | // Assert.AreApproximatelyEqual(sm.ReadFloat32(3).Item1, 0); 39 | // sm.WriteFloat32(3, 42); 40 | // comparer.AreApproximatelyEqual(sm.ReadFloat32(3).Item1, 42); 41 | 42 | sm.WriteString(10, "forty-two"); 43 | Assert.AreEqual(sm.ReadString(10).Item1, "forty-two"); 44 | 45 | var path = Path.Combine(Path.GetTempPath(), "python_unity_shared_memory/test"); 46 | Assert.True(File.Exists(path)); 47 | sm.Delete(); 48 | Assert.False(File.Exists(path)); 49 | } 50 | 51 | [Test] 52 | public void TestTimeout(){ 53 | SharedMemory.DeleteFiles("test"); 54 | var sm = new SharedMemory("test", 100, true, 0.1f); 55 | sm.WriteBool(0, true); 56 | sm.GiveControl(wait:false); 57 | Assert.Throws(() => sm.ReadBool(0)); 58 | } 59 | 60 | [Test] 61 | public void TestTwoUnity(){ 62 | SharedMemory.DeleteFiles("test"); 63 | var sm0 = new SharedMemory("test", 100, true, 30); 64 | var sm1 = new SharedMemory("test", 100, false, 30); 65 | sm0.WriteString(42, "foo"); 66 | Assert.AreEqual(sm1.ReadString(42).Item1, "foo"); 67 | SharedMemory.DeleteFiles("test"); 68 | } 69 | 70 | [Test] 71 | public void TestResize(){ 72 | SharedMemory.DeleteFiles("test"); 73 | var sm0 = new SharedMemory("test", 100, true, 30); 74 | var sm1 = new SharedMemory("test", 100, false, 30); 75 | sm0.WriteString(42, "foo"); 76 | Assert.AreEqual(sm1.ReadString(42).Item1, "foo"); 77 | sm1.Resize(101); 78 | Assert.AreEqual(sm0.ReadString(42).Item1, "foo"); 79 | Assert.AreEqual(sm1.ReadString(42).Item1, "foo"); 80 | sm0.Close(); 81 | Assert.Throws(() => sm1.ReadBool(0)); 82 | SharedMemory.DeleteFiles("test"); 83 | } 84 | } 85 | } -------------------------------------------------------------------------------- /com.python-unity-shared-memory/Tests/Editor/Test_SM.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 24252772c9c7e420fb4d87c8e64fc622 3 | MonoImporter: 4 | externalObjects: {} 5 | serializedVersion: 2 6 | defaultReferences: [] 7 | executionOrder: 0 8 | icon: {instanceID: 0} 9 | userData: 10 | assetBundleName: 11 | assetBundleVariant: 12 | -------------------------------------------------------------------------------- /com.python-unity-shared-memory/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "com.python-unity-shared-memory", 3 | "displayName": "Python Unity Shared Memory", 4 | "version": "0.1.0", 5 | "unity": "2019.1", 6 | "description": "Communicate data between C# and Python via shared memory", 7 | "dependencies": { 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /com.python-unity-shared-memory/package.json.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 06fd9a43e1df94956817f66408c1e5cd 3 | PackageManifestImporter: 4 | externalObjects: {} 5 | userData: 6 | assetBundleName: 7 | assetBundleVariant: 8 | -------------------------------------------------------------------------------- /python_unity_shared_memory/python_unity_shared_memory/__init__.py: -------------------------------------------------------------------------------- 1 | import os 2 | import tempfile 3 | import mmap 4 | import struct 5 | import time 6 | from typing import Tuple 7 | import glob 8 | 9 | class _Core: 10 | DIR = "python_unity_shared_memory" 11 | 12 | def __init__(self, name:str, capacity:int, create_new:bool): 13 | """ 14 | Creates (if `create_new` is True) or opens (if `create_new` 15 | is False) the file `name` with size `capacity` 16 | in bytes (if opening a file `capacity cannot be bigger than 17 | the file) 18 | """ 19 | self.opened = False 20 | if len(name) < 1: 21 | raise ValueError("name must be at least one character") 22 | directory = os.path.join(tempfile.gettempdir(), self.DIR) 23 | if not os.path.exists(directory): 24 | os.makedirs(directory) 25 | # At this point, the directory DIR has been created 26 | self.file_path = os.path.join(directory, name) 27 | if create_new: 28 | if os.path.exists(self.file_path): 29 | raise FileExistsError(f"The file {name} already exists.") 30 | # Clear any data present in the file within capacity 31 | empty_array = bytearray(capacity) 32 | with open(self.file_path, "w+b") as f: 33 | f.write(empty_array) 34 | with open(self.file_path, "r+b") as f: 35 | self.mem = mmap.mmap(f.fileno(), 0) #0 means whole file 36 | if len(self.mem) < capacity: 37 | raise ValueError( 38 | f"The file {name} is smaller than the requested capacity" 39 | ) 40 | self.opened = True 41 | 42 | def close(self) -> None: 43 | """ 44 | Closes the file and removes access. Does not delete. 45 | """ 46 | if self.opened: 47 | self.mem.close() 48 | self.opened = False 49 | 50 | def delete(self): 51 | self.close() 52 | try: 53 | os.remove(self.file_path) 54 | except BaseException: 55 | pass 56 | 57 | def __enter__(self): 58 | return self 59 | 60 | def __exit__(self, *a): 61 | self.delete() 62 | 63 | 64 | def read_int32(self, offset) -> Tuple[int, int]: 65 | return struct.unpack_from(" Tuple[bool, int]: 67 | return struct.unpack_from("Tuple[bytes, int]: 69 | return self.mem[offset:offset+length], offset+length 70 | 71 | 72 | # Now the write methods 73 | # write methods have argument offset and value and return a new offset 74 | def write_int32(self, offset:int, value:int) -> int: 75 | struct.pack_into(" int: 78 | struct.pack_into(" int: 81 | length = len(data) 82 | self.mem[offset:offset+length] = data 83 | return offset+length 84 | 85 | def delete_files(prefix:str): 86 | directory = os.path.join(tempfile.gettempdir(), _Core.DIR) 87 | if not os.path.exists(directory): 88 | os.makedirs(directory) 89 | file_path = os.path.join(directory, prefix) 90 | for f in glob.glob(file_path + "*"): 91 | os.remove(f) 92 | 93 | class SharedMemory: 94 | 95 | _VERSION = 1 96 | _VERSION_OFFSET = 0 97 | _FILE_NUMBER_OFFSET = 4 98 | _CAPACITY_OFFSET = 8 99 | _PYTHON_ACTIVE_OFFSET = 12 100 | _UNITY_ACTIVE_OFFSET = 13 101 | _CLOSE_OFFSET = 14 102 | def __init__( 103 | self, 104 | prefix:str, 105 | capacity:int, 106 | create_new:bool, 107 | timeout: int = -1 108 | ): 109 | """ 110 | DATA | TYPE | OFFSET 111 | ______________|_________|_______ 112 | VERSION | int | 0 113 | FILE_NUMBER | int | 4 114 | CAPACITY | int | 8 115 | PYTHON_ACTIVE | bool | 12 116 | UNITY_ACTIVE | bool | 13 117 | CLOSE | bool | 14 118 | ________________________________ 119 | 120 | """ 121 | self._name = prefix 122 | self._timeout = timeout 123 | if self._name[-1] == '_': 124 | raise ValueError( 125 | f"The name of the shared memory {name} cannot end with _." 126 | ) 127 | self._hook = _Core(self._name, self._CLOSE_OFFSET+1, create_new) 128 | if create_new: 129 | #must write the hook's data 130 | self._version = self._VERSION 131 | self._file_number = 1 132 | self._capacity = capacity 133 | self._hook.write_bool(self._PYTHON_ACTIVE_OFFSET, True) # Python is active 134 | else: 135 | if self._version != self._VERSION: 136 | raise RuntimeError( 137 | f"Incompatible versions between Unity (v{self._version}) and Python (v{self._VERSION})" 138 | ) 139 | self._last_file_number = self._file_number 140 | self._current = _Core(self._name + '_' * self._file_number, self._capacity, create_new) 141 | self.wait_unblocked() 142 | 143 | def resize(self, capacity:int): 144 | self._file_number += 1 145 | old_capacity = self._capacity 146 | if capacity < old_capacity: 147 | raise ValueError("New capacity must be greater than previous") 148 | self._capacity = capacity 149 | new_current = _Core(self._name + '_' * self._file_number, self._capacity, True) 150 | new_current.mem[0:old_capacity] = self._current.mem[0:capacity] 151 | self._current = new_current 152 | self._last_file_number = self._file_number 153 | 154 | def wait_unblocked(self): 155 | if self.blocked: 156 | t0 = time.time() 157 | iteration = 0 158 | while self.blocked and self._active: 159 | if iteration % 1e8 == 0 and self._timeout > 0: 160 | if time.time()- t0> self._timeout: 161 | self.delete() 162 | raise TimeoutError("Communication took too long.") 163 | if not self._active: 164 | self.delete() 165 | raise ConnectionError("Unity has stopped.") 166 | if self._last_file_number != self._file_number: 167 | self._last_file_number = self._file_number 168 | self._current.delete() 169 | self._current = _Core(self._name + '_' * self._file_number, self._capacity, False) 170 | 171 | def close(self) -> None: 172 | try: 173 | self._hook.write_bool(self._CLOSE_OFFSET, True) 174 | except BaseException: 175 | pass 176 | self._hook.close() 177 | self._current.close() 178 | 179 | def delete(self): 180 | self.close() 181 | self._hook.delete() 182 | self._current.delete() 183 | 184 | def __enter__(self): 185 | return self 186 | 187 | def __exit__(self, *a): 188 | self.delete() 189 | 190 | 191 | @property 192 | def _version(self): 193 | return self._hook.read_int32(self._VERSION_OFFSET)[0] 194 | @_version.setter 195 | def _version(self, value): 196 | self._hook.write_int32(self._VERSION_OFFSET, value) 197 | @property 198 | def _file_number(self): 199 | return self._hook.read_int32(self._FILE_NUMBER_OFFSET)[0] 200 | @_file_number.setter 201 | def _file_number(self, value): 202 | self._hook.write_int32(self._FILE_NUMBER_OFFSET, value) 203 | @property 204 | def _capacity(self): 205 | return self._hook.read_int32(self._CAPACITY_OFFSET)[0] 206 | @_capacity.setter 207 | def _capacity(self, value): 208 | self._hook.write_int32(self._CAPACITY_OFFSET, value) 209 | @property 210 | def _active(self): 211 | return not self._hook.read_bool(self._CLOSE_OFFSET)[0] 212 | 213 | def unsafe_signal_unity_unblocked(self): 214 | self._hook.write_bool(self._UNITY_ACTIVE_OFFSET, True) 215 | def unsafe_signal_python_blocked(self): 216 | self._hook.write_bool(self._PYTHON_ACTIVE_OFFSET, False) 217 | def give_control(self, wait:bool = True): 218 | self.wait_unblocked() 219 | self.unsafe_signal_python_blocked() 220 | self.unsafe_signal_unity_unblocked() 221 | if wait: 222 | self.wait_unblocked() 223 | @property 224 | def blocked(self): 225 | return not self._hook.read_bool(self._PYTHON_ACTIVE_OFFSET)[0] 226 | 227 | 228 | # This region is all the read files 229 | # You can add more here 230 | # All read methods return a value and the new offset 231 | def read_int32(self, offset) -> Tuple[int, int]: 232 | self.wait_unblocked() 233 | return self._current.read_int32(offset) 234 | def read_bool(self, offset) -> Tuple[bool, int]: 235 | self.wait_unblocked() 236 | return self._current.read_bool(offset) 237 | def read_bytes(self, offset, length)-> Tuple[bytes, int]: 238 | self.wait_unblocked() 239 | return self._current.read_bytes(offset, length) 240 | def read_float32(self, offset) -> Tuple[float, int]: 241 | self.wait_unblocked() 242 | return struct.unpack_from(" Tuple[str, int]: 244 | """ 245 | The string is encoded with its length first is ASCII 246 | """ 247 | self.wait_unblocked() 248 | length, offset = self.read_int32(offset) 249 | data, offset = self.read_bytes(offset, length) 250 | return data.decode("ascii"), offset 251 | 252 | 253 | # Now the write methods 254 | # write methods have argument offset and value and return a new offset 255 | def write_int32(self, offset:int, value:int) -> int: 256 | self.wait_unblocked() 257 | return self._current.write_int32(offset, value) 258 | def write_bool(self, offset:int, value:bool) -> int: 259 | self.wait_unblocked() 260 | return self._current.write_bool(offset, value) 261 | def write_bytes(self, offset: int, data:bytes) -> int: 262 | return self._current.write_bytes(offset, data) 263 | def write_float32(self, offset:int, value:float) -> int: 264 | self.wait_unblocked() 265 | struct.pack_into(" int: 268 | self.wait_unblocked() 269 | length = len(value) 270 | offset = self.write_int32(offset, length) 271 | self._current.mem[offset:offset+length] = value.encode("ascii") 272 | return offset + length -------------------------------------------------------------------------------- /python_unity_shared_memory/setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup, find_packages 2 | 3 | setup( 4 | name="python_unity_shared_memory", 5 | version="0.1.0", 6 | description="General purpose shared memory communication between Python and Unity", 7 | url="https://github.com/vincentpierre/PythonUnitySharedMemory", 8 | author="Vincent-Pierre Berges", 9 | install_requires=[], 10 | python_requires=">=3.6", 11 | packages=find_packages( 12 | exclude=["test"] 13 | ), 14 | ) 15 | -------------------------------------------------------------------------------- /python_unity_shared_memory/test/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vincentpierre/PythonUnitySharedMemory/4a8e2cb662a022371a22fea0f27449606a16d787/python_unity_shared_memory/test/__init__.py -------------------------------------------------------------------------------- /python_unity_shared_memory/test/test_integration.py: -------------------------------------------------------------------------------- 1 | from python_unity_shared_memory import SharedMemory, delete_files 2 | import os 3 | import pytest 4 | 5 | def test_integration(): 6 | sm = SharedMemory("test", 100, False, 30) 7 | # 8 | assert sm.read_string(42)[0] == "foo" 9 | sm.write_string(42, "bar") 10 | assert sm.read_string(42)[0] == "bar" 11 | # 12 | sm.give_control() # bock u2 13 | # 14 | assert sm.read_string(42)[0] == "foo" 15 | 16 | sm.resize(200) 17 | sm.write_string(142, "bar142") 18 | # 19 | sm.give_control() # block u4 20 | # 21 | sm.resize(400) 22 | sm.write_string(342, "bar342") 23 | # 24 | sm.give_control(wait=False) # block u6 25 | 26 | -------------------------------------------------------------------------------- /python_unity_shared_memory/test/test_sm.py: -------------------------------------------------------------------------------- 1 | from python_unity_shared_memory import SharedMemory, delete_files 2 | import os 3 | import pytest 4 | 5 | def test_create(): 6 | delete_files("test") 7 | sm = SharedMemory("test", 100, True, 30) 8 | sm.close() 9 | assert os.path.exists(sm._hook.file_path) 10 | delete_files("test") 11 | assert not os.path.exists(sm._hook.file_path) 12 | 13 | def test_read_write(): 14 | delete_files("test") 15 | sm = SharedMemory("test", 100, True, 30) 16 | 17 | assert not sm.read_bool(0)[0] 18 | sm.write_bool(0, True) 19 | assert sm.read_bool(0)[0] 20 | 21 | assert sm.read_int32(3)[0] == 0 22 | sm.write_int32(3, 42) 23 | assert sm.read_int32(3)[0] == 42 24 | 25 | assert sm.read_float32(10)[0] == 0 26 | sm.write_float32(10, 42) 27 | assert sm.read_float32(10)[0] == 42 28 | 29 | sm.write_string(10, "forty-two") 30 | assert sm.read_string(10)[0] == "forty-two" 31 | 32 | assert os.path.exists(sm._hook.file_path) 33 | sm.delete() 34 | assert not os.path.exists(sm._hook.file_path) 35 | 36 | def test_timeout(): 37 | delete_files("test") 38 | sm = SharedMemory("test", 100, True, 0.01) 39 | sm.write_bool(0, True) 40 | sm.give_control(wait = False) 41 | with pytest.raises(TimeoutError): 42 | sm.read_bool(0) 43 | 44 | def test_two_python(): 45 | delete_files("test") 46 | sm0 = SharedMemory("test", 100, True, 30) 47 | sm1 = SharedMemory("test", 100, False, 30) 48 | sm0.write_string(42, "foo") 49 | assert sm1.read_string(42)[0] == "foo" 50 | delete_files("test") 51 | 52 | def test_resize(): 53 | delete_files("test") 54 | sm0 = SharedMemory("test", 100, True, 0) 55 | sm1 = SharedMemory("test", 100, False, 0) 56 | sm0.write_string(42, "foo") 57 | assert sm1.read_string(42)[0] == "foo" 58 | sm1.resize(101) 59 | assert sm0.read_string(42)[0] == "foo" 60 | assert sm1.read_string(42)[0] == "foo" 61 | 62 | sm0.close() 63 | with pytest.raises(ConnectionError): 64 | sm1.read_bool(0) 65 | delete_files("test") 66 | --------------------------------------------------------------------------------