Code interaction conversion method and system
By using the MinGW32 compiler in the C# program to compile the C++ code into a dynamic link library and interacting through sockets, the complexity of dynamically changing the C++ code in the C# program is solved, cross-language execution and efficient data exchange are achieved, and the software is improved. Development flexibility and maintainability.
Patent Information
- Application Number
- CN202411138038.5
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2024-08-19
- Publication Date
- 2024-10-11
- Estimated Expiration
- 2044-08-19
AI Technical Summary
In software development, especially in mixed programming environments, dynamically changing and executing C++ code directly within a packaged C# program is a complex and challenging task because of significant differences in the behavior of C# and C++ at compile and runtime. Differences, and usually they each follow different memory management and compilation models, make it impossible to dynamically change C++ code directly in C# programs using traditional methods.
By using the built-in MinGW32 compiler in the C# program to compile the C++ code into a dynamic link library file, and interacting with the DLL execution program through the socket mechanism, cross-language dynamic compilation and execution is achieved, allowing input at any time while the C# program is running. Or change the C++ code.
It realizes the ability to dynamically execute C++ code in C# programs, improves the flexibility, dynamics, scalability and maintainability of software development, breaks the barriers between programming languages, and enables programs or code snippets in different languages to Work collaboratively.
Smart Images

Figure CN118760435A_ABST
Abstract
Description
Technical Field
[0001] The present invention relates to the field of programming technology, and in particular to a code interactive conversion method and system. Background Art
[0002] Currently, in software development, especially when it comes to mixed programming (such as interoperation between C# and C++), dynamically changing and executing C++ code directly in a packaged C# program is indeed a complex and challenging task. This is mainly because C# and C++ have significant differences in their behaviors during compilation and runtime, and usually they each follow different memory management and compilation models.
[0003] As a high-level programming language, C# runs on the .NET framework or .NET Core, and uses just-in-time compilation (JIT) or pre-compilation (AOT) to convert source code into intermediate language (IL), which is then converted into machine code by CLR (Common Language Runtime) for execution. C# programs will perform type safety checks and garbage collection during compilation to ensure the stability and security of the program. As a programming language closer to hardware, C++ directly compiles source code into machine code during compilation without going through an intermediate layer. This makes C++ programs run more efficiently, but it also requires developers to have a deeper understanding of memory management, pointer operations, etc.
[0004] Once C++ code is compiled into an executable file or DLL, its machine code is fixed and cannot be modified directly unless it is recompiled. This means that it is impossible to modify C++ code directly in C# and make it effective. C# and C++ programs usually run in different contexts in memory (unless through specific bridging mechanisms such as P / Invoke or C++ / CLI), which further increases the difficulty of directly modifying C++ code. Even if a method can be found to modify C++ code at runtime, this practice will bring serious security vulnerabilities because it destroys the integrity and predictability of the code. Traditional methods cannot dynamically change the execution of C++ code directly in a packaged C# program. Therefore, designing a solution that can perform code interactive conversion has become a technical problem that needs to be solved urgently by those skilled in the art. Summary of the invention
[0005] In view of the above defects, an embodiment of the present invention discloses a code interactive conversion method, which can significantly improve the flexibility of the system.
[0006] The first aspect of the embodiment of the present invention discloses a code interactive conversion method, including: In a main program running in a first programming language, a code program compiled in a second programming language that needs to be dynamically executed is obtained; In the main program, the code program compiled based on the second programming language is compiled into a corresponding dynamic link library file using the built-in MinGW32 compiler, and an execution program for loading and executing the compiled dynamic link library file is created; In the main program, a corresponding execution program is started, a dynamic link library file is loaded, and a code program compiled based on the second programming language is executed; The socket mechanism is enabled in the main program to connect to the execution program of the dynamic link library file to send data to be processed by the code program compiled based on the second programming language through the socket mechanism, and receive the execution result of the code program compiled based on the second programming language.
[0007] As an optional implementation manner, in the first aspect of the embodiment of the present invention, after receiving the result of executing the code program compiled based on the second programming language, the method further includes: In the main program, call the close function provided by the socket API to close the socket connection; Call the process management API in the main program to close the DLL execution program; After closing the DLL execution program, unload the corresponding DLL.
[0008] As an optional implementation, in the first aspect of the embodiment of the present invention, the step of obtaining, in a main program running in a first programming language, a code program compiled in a second programming language that needs to be dynamically executed includes: In the main program running based on C#, obtain the code program compiled based on C++ that needs to be dynamically executed; The method of opening a socket mechanism to connect to the execution program of the dynamic link library file to send data to be processed by the code program compiled based on the second programming language through the socket mechanism, and receiving the result of executing the code program compiled based on the second programming language, includes: Start the DLL execution program, the main program sends the data that needs to be processed by the C++ code through the socket, and receives the result of the C++ code execution; after receiving the data, the DLL execution program calls the corresponding C++ function for processing and returns the result to the C# main program. After receiving the result of the C++ code execution, the C# main program processes it as needed.
[0009] As an optional implementation manner, in the first aspect of the embodiment of the present invention, starting the corresponding execution program in the main program includes: Use the windowless method to start the corresponding execution program in the main program.
[0010] As an optional implementation, in the first aspect of the embodiment of the present invention, the code interactive conversion method is applied to a programming robot, and after receiving the result of executing the code program compiled based on the second programming language, it also includes: Use the received data to perform corresponding simulation actions to simulate operations or responses in the actual environment.
[0011] As an optional implementation, in the first aspect of the embodiment of the present invention, the method of using the built-in MinGW32 compiler in the main program to compile the code program compiled based on the second programming language into a corresponding dynamic link library file includes: Set the actual path and environment variables of the MinGW32 compiler in the main program; Set the source code file and target output directory; if the target output directory does not exist, create a new output directory and use the MinGW32 compiler to compile the source code into the corresponding dynamic link library file.
[0012] A second aspect of an embodiment of the present invention discloses a code interactive conversion system, including: An acquisition module is used to acquire a code program compiled in a second programming language that needs to be dynamically executed in a main program running in a first programming language; Compilation module: used to compile the code program compiled based on the second programming language into a corresponding dynamic link library file using the built-in MinGW32 compiler in the main program, and create an execution program for loading and executing the compiled dynamic link library file at the main program; the execution program here can be dynamically created when compiling C++, or can be developed when developing the main program. The execution program here is more preferably developed when developing the main program; The startup loading module is used to start the corresponding execution program in the main program, load the dynamic link library file, and execute the code program compiled based on the second programming language; Interaction module: used to open the socket mechanism in the main program to connect the execution program of the dynamic link library file to send data that needs to be processed by the code program compiled based on the second programming language through the socket mechanism, and receive the execution result of the code program compiled based on the second programming language.
[0013] As an optional implementation, in the second aspect of the embodiment of the present invention, after receiving the result of executing the code program compiled based on the second programming language, the method further includes: The first closing module: used to call the closing function provided by the socket API in the main program to close the socket connection; The second closing module: used to call the process management API in the main program to close the DLL execution program; Uninstall module: used to uninstall the corresponding DLL after closing the DLL execution program.
[0014] Compared with the prior art, the embodiments of the present invention have the following beneficial effects: The code interactive conversion method in the embodiment of the present invention can input or change the C++ code and execute this code at any time during the running of the C# program; the method in the embodiment of the present invention improves the flexibility, dynamism, scalability and maintainability of software development through technical means such as cross-language execution, dynamic compilation and execution, efficient data interaction, modularization and decoupling. BRIEF DESCRIPTION OF THE DRAWINGS
[0015] In order to more clearly illustrate the technical solutions in the embodiments of the present invention, the drawings required for use in the embodiments will be briefly introduced below. Obviously, the drawings described below are only some embodiments of the present invention. For ordinary technicians in this field, other drawings can be obtained based on these drawings without creative work.
[0016] Figure 1 It is a flowchart of the code interactive conversion method disclosed in an embodiment of the present invention; Figure 2 It is a flowchart of the closing and uninstalling steps disclosed in an embodiment of the present invention; Figure 3 This is a specific flow chart of the code interactive conversion method disclosed in the embodiment of the present invention. Figure 4 It is a structural schematic diagram of a code interactive conversion system provided by an embodiment of the present invention; Figure 5 It is a structural schematic diagram of an electronic device provided by an embodiment of the present invention. DETAILED DESCRIPTION
[0017] The following will be combined with the drawings in the embodiments of the present invention to clearly and completely describe the technical solutions in the embodiments of the present invention. Obviously, the described embodiments are only part of the embodiments of the present invention, not all of the embodiments. Based on the embodiments of the present invention, all other embodiments obtained by ordinary technicians in this field without creative work are within the scope of protection of the present invention.
[0018] It should be noted that the terms "first", "second", "third", "fourth", etc. in the specification and claims of the present invention are used to distinguish different objects rather than to describe a specific order. The terms "including" and "having" in the embodiments of the present invention and any variations thereof are intended to cover non-exclusive inclusions. For example, a process, method, system, product or device including a series of steps or units is not necessarily limited to those steps or units clearly listed, but may include other steps or units that are not clearly listed or inherent to these processes, methods, products or devices.
[0019] Traditional methods cannot dynamically change and execute C++ code directly in a packaged C# program. The embodiment of the present invention discloses a code interactive conversion method, system, electronic device and storage medium. By building a C++ compiler and developing a subroutine to execute dll, the C++ code is compiled into dll, and then the subroutine is started to load the dll. The main program communicates with the subroutine through a socket to exchange data, and the subroutine is closed after execution. In this way, it is possible to input or change C++ code at any time and execute this code during the running of the C# program.
[0020] Embodiment 1 See also Figure 1 , Figure 1 It is a flow chart of the code interactive conversion method disclosed in the embodiment of the present invention. Among them, the execution subject of the method described in the embodiment of the present invention is an execution subject composed of software and / or hardware, and the execution subject can receive relevant information by wired or / and wireless means, and can send certain instructions. Of course, it can also have certain processing functions and storage functions. The execution subject can control multiple devices, such as a remote physical server or cloud server and related software, or it can be a local host or server and related software that performs related operations on a device placed somewhere. In some scenarios, multiple storage devices can also be controlled, and the storage devices can be placed in the same place or different places as the devices. For example Figure 1 , Figure 2 and Figure 3 As shown, the code-based interactive conversion method includes the following steps: S101: In a main program running in a first programming language, a code program compiled in a second programming language that needs to be dynamically executed is obtained; in a C# main program, a mechanism needs to be provided to obtain C++ code provided by a user or an external system. This can be achieved through a text input box, a file upload interface, a network request, or other methods. The obtained C++ code will be stored in memory as a string, waiting for subsequent processing.
[0021] S102: In the main program, the code program compiled based on the second programming language is compiled into a corresponding dynamic link library file using the built-in MinGW32 compiler, and an execution program for loading and executing the compiled dynamic link library file is created; the relevant executable files and library files of the MinGW32 compiler are included in the installation directory of the C# program. In this way, when the C++ code needs to be compiled, the program can directly call these files without the user having to install the compiler separately. Create a separate program that is responsible for loading and executing the compiled DLL file. This program can be written in C# or C++ / CLI to make it easier to interoperate with the DLL. Some interfaces need to be defined in this program to receive input from the main program and send output.
[0022] S103: Start the corresponding execution program in the main program, load the dynamic link library file, and execute the code program compiled based on the second programming language; write a batch script or use the System.Diagnostics.Process class of C# to call the MinGW32 compiler. The obtained C++ code needs to be passed to the compiler as input, and the output is specified as a DLL file. Some compilation options may need to be set during the compilation process, such as optimization level, debug information generation, etc.
[0023] S104: In the main program, a socket mechanism is enabled to connect to the execution program of the dynamic link library file to send data to be processed by the code program compiled based on the second programming language through the socket mechanism, and receive the execution result of the code program compiled based on the second programming language. A socket connection is established between the main program and the DLL execution program. You can use the Socket class in the System.Net.Sockets namespace to achieve this. The main program sends the function name, parameters and other data to be executed to the DLL execution program through the Socket, and receives the execution result. You need to define a communication protocol to ensure the correct transmission and parsing of data. Once the C++ code is executed and all the required data has been transmitted through the Socket, the main program needs to close the Socket connection. This can be achieved by calling the Close method of the Socket class. At the same time, the main program needs to close the DLL execution program, which can be achieved by calling the Kill method of the Process class. Finally, you can choose to delete the compiled DLL file to clean up resources.
[0024] The above method implements the execution of a code program written in a second programming language in an environment of a first programming language. This breaks down the barriers between programming languages, allowing programs or code snippets written in different programming languages to work together in the same environment, thereby improving the flexibility and reusability of software development.
[0025] Through the built-in MinGW32 compiler, the method can dynamically compile the code of the second programming language into a dynamic link library file and create an execution program to load and execute these library files. This dynamic compilation and execution capability enables the software to compile and execute new or modified code in real time as needed, enhancing the dynamicity and scalability of the software.
[0026] The method realizes data interaction between the main program and the dynamic link library file execution program through the socket mechanism. This mechanism allows the main program to send data to the code program based on the second programming language for processing and receive the processing results, thus realizing efficient and flexible data exchange and communication.
[0027] By compiling the code based on the second programming language into a dynamic link library file and communicating through the socket mechanism, the method realizes the decoupling and independent deployment of code modules. This allows different modules or components to be independently developed, tested and deployed, improving the efficiency and maintainability of software development.
[0028] More preferably, after receiving the result of executing the code program compiled in the second programming language, the method further includes: S105: calling the close function provided by the socket API in the main program to close the socket connection; by calling the close function provided by the socket API, the system resources occupied by the socket connection can be released, resource leakage can be avoided, and the stability and performance of the system can be ensured.
[0029] S106: calling the process management API in the main program to close the DLL execution program; using the process management API to close the DLL execution program can ensure that the memory, file handles and other resources occupied by the program are correctly released to prevent memory leaks and other resource occupation problems.
[0030] S107: After closing the DLL execution program, uninstalling the corresponding DLL. After closing the DLL execution program, uninstalling the corresponding DLL file can further release resources related to the DLL, including memory, file handles, etc., to ensure effective management of system resources.
[0031] By closing the socket connection, closing the DLL execution program, and uninstalling the DLL in a timely manner, you can avoid system crashes or performance degradation caused by excessive resource usage, thereby improving system stability and reliability. Timely releasing and uninstalling unused resources can reduce potential security risks, such as preventing malicious code from attacking by exploiting unclosed connections or uninstalled DLLs. Explicitly including resource release and uninstallation logic in the code can make the code neater and more orderly, making it easier to maintain and expand later.
[0032] More preferably, the step of obtaining a code program compiled in a second programming language that needs to be dynamically executed in a main program running in a first programming language includes: In the main program running based on C#, obtain the code program compiled based on C++ that needs to be dynamically executed; The method of opening a socket mechanism to connect to the execution program of the dynamic link library file to send data to be processed by the code program compiled based on the second programming language through the socket mechanism, and receiving the result of executing the code program compiled based on the second programming language, includes: Start the DLL execution program, the main program sends the data that needs to be processed by the C++ code through the socket, and receives the result of the C++ code execution; after receiving the data, the DLL execution program calls the corresponding C++ function for processing and returns the result to the C# main program. After receiving the result of the C++ code execution, the C# main program processes it as needed.
[0033] It allows you to enter or change C++ code at any time while the C# program is running, and execute this code. It combines the ease of use of C# and the high performance of C++, and is suitable for scenarios that require high-performance computing but want to maintain the ease of use of the program. By dynamically loading DLLs, you can easily expand the functionality of the program without recompiling the entire program, allowing you to take advantage of C++ in a C# environment and achieve cross-language programming and code reuse.
[0034] Since there is no need to start an external process, it may have better performance, especially if C++ code needs to be executed frequently. Starting and managing external processes consumes additional resources and may introduce performance overhead.
[0035] This approach within the main program provides greater flexibility because it is easier to modify and extend the way the C++ code is executed without changing the external program. If you need to modify the way the C++ code is executed, you may need to recompile and deploy the external program, which increases the complexity of maintenance.
[0036] Since the execution of C++ code is done in the context of the main program, it is easier to catch and handle errors that occur during execution and debug. Error handling and debugging outside the main program may be more difficult because of the need to deal with cross-process communication and synchronization issues.
[0037] More preferably, starting the corresponding execution program in the main program includes: Use the windowless method to start the corresponding execution program in the main program.
[0038] Starting the execution program in a windowless manner in an embodiment of the present invention can avoid additional windows popping up, thereby not interfering with the user's current operating interface and improving the user experience. Not creating additional windows can reduce the occupation of system resources, including memory and CPU resources, which is particularly important for resource-limited environments or applications that need to run efficiently. The windowless mode allows the execution program to run in the background, which is very useful for applications that need to perform long-running tasks or do not require user interaction. The windowless execution program can reduce the user's interaction opportunities with potential malware, thereby reducing security risks. In the C# main program, use the System.Diagnostics.Process class to start the DLL execution program. You need to set the CreateNoWindow property of ProcessStartInfo to true in order to run the program in windowless mode. At the same time, pass the compiled DLL path as a parameter to the program.
[0039] More preferably, the code interactive conversion method is applied to a programming robot, and after receiving the result of executing the code program compiled in the second programming language, it further includes: Use the received data to perform corresponding simulation actions to simulate operations or responses in the actual environment.
[0040] By using the code interactive conversion method, the programming robot can more easily integrate and use codes written in different programming languages, thereby increasing its flexibility and scalability. The simulated actions of the programming robot in the virtual environment can provide more intuitive and easier to understand feedback, thus helping users better understand and use the programming robot.
[0041] More preferably, the method of using the built-in MinGW32 compiler in the main program to compile the code program compiled based on the second programming language into a corresponding dynamic link library file includes: Set the actual path and environment variables of the MinGW32 compiler in the main program; Set the source code file and target output directory; if the target output directory does not exist, create a new output directory and use the MinGW32 compiler to compile the source code into the corresponding dynamic link library file.
[0042] The following key codes are disclosed in the embodiments of the present invention and briefly described: / / 1. The main program receives data and controls the simulation private void HandleMessageReceived(byte[] data, NetworkStreamclientStream) { / / Logic for processing received messages string msg = Encoding.UTF8.GetString(data); string[] line = msg.Split(';'); / / UnityEngine.Debug.Log(CarHJ.GetInstance().rcuTime + "" + msg); if (runStart) { runStart = false; Loom.QueueOnMainThread(() => { OnStartAction?.Invoke(""); string rdata = RCU.GetAllPortData(); / / UnityEngine.Debug.Log("ready send: " + rdata); byte[] d = Encoding.UTF8.GetBytes(rdata); SocketServerUtility.SendData(d, clientStream); }); } if (line.Length>0) { foreach (var item in line) { string[] cmd = item.Split(','); if (cmd.Length>0) { switch (cmd[0]) { case "SetLightSensorLed": RCU.SetLightSensorLed(int.Parse(cmd[1]), int.Parse(cmd[2])); break; case "SetMotor": RCU.SetMotor(int.Parse(cmd[1]), int.Parse(cmd[2])); break; case "SetMotorServo": RCU.SetMotorServo(int.Parse(cmd[1]), int.Parse(cmd[2]), int.Parse(cmd[3])); break; case "SetMotorStraightAngle": RCU.SetMotorStraightAngle(int.Parse(cmd[1]), int.Parse(cmd[2]),int.Parse(cmd[3]), int.Parse(cmd[4])); break; case "SetServo": RCU.SetServo(int.Parse(cmd[1]), int.Parse(cmd[2])); break; case "SetServoTime": RCU.SetServoTime(int.Parse(cmd[1]), int.Parse(cmd[2]), int.Parse(cmd[3])); break; case "Set3CLed": RCU.Set3CLed(int.Parse(cmd[1]), int.Parse(cmd[2])); break; case "SetMp3Play": RCU.SetMp3Play(int.Parse(cmd[1])); break; case "SetMp3Suspend": RCU.SetMp3Suspend(); break; case "SetInBeep": RCU.SetInBeep(int.Parse(cmd[1])); break; case "SetLizard": RCU.SetLizard(int.Parse(cmd[1])); break; case "UpdateVar": RCU.ShowVar(cmd[1], cmd[2]); break; case "Error": Loom.QueueOnMainThread(() => { OnError?.Invoke("RunError," + item.Replace("Error,", "")); }); break; } } } if (!msg.Equals("Start;")) { string rdata = RCU.GetAllPortData(); / / UnityEngine.Debug.Log("ready send: " + rdata); byte[] d = Encoding.UTF8.GetBytes(rdata); SocketServerUtility.SendData(d, clientStream); } } } / / 2. Interface class in C++: #include "jmd.h" #include "utils.h" #include <map> #include<stddef.h> #include<string.h> #include<stdio.h> #include<stdlib.h> #include <iostream> #include <sstream> #include <array> #include <vector> #include <mutex> #include <chrono> #include<time.h> #ifdef _WIN32 #include<windows.h> #else #include<unistd.h> #endif / / _WIN32 / / Record the current time (in milliseconds) std::chrono::time_point<std::chrono::high_resolution_clock> sysTime; / * Get controller time, timing in C++ * / EXPORT long GetSysTime() { std::chrono::duration<double, std::milli> a = std::chrono::high_resolution_clock::now() - sysTime; / / printf("a:%d\nsysTime:%d\n", a.count, sysTime); return a.count(); } / / Reset controller time to zero EXPORT void SetSysTime() { sysTime = std::chrono::high_resolution_clock::now(); } / / / <summary> / / / Return photoelectric 0-4095 / / / < / summary> / / / <param name="port"> / / / <returns>< / returns> EXPORT int GetLightSensor(int port) { int result = 0; / / Convert the floating point number to a string and assign it to globalSensorData[port] if (port>= 1&&port<= 8) { / / Lock g_mutex.lock(); std::string inputString = globalSensorData[port + 3]; std::vector <std::string>tokens = jmd_splitString(globalSensorData[port + 3], ','); if (tokens.size()>= 2&&tokens[0] == "Light") { result = std::stoi(tokens[1]); } / / Release the lock g_mutex.unlock(); } return result; } / / / <summary> / / / Returns photoelectric 0 or 1, black 1, white 0 / / / < / summary> / / / <param name="port"> / / / <returns>< / returns> EXPORT int GetLightSensorData(int port) { int grayscale = GetLightSensor(port); return grayscale>1474 ? 0 : 1; } / / Set the photoelectric light switch EXPORT void SetLightSensorLed(int port, int state) { / / Function to set data to add to another string if (port>= 1&&port<= 8) { / / Lock g_mutex.lock(); setMap["P" + std::to_string(port)] = "SetLightSensorLed," + std::to_string(port) + "," + std::to_string(state); / / Release the lock g_mutex.unlock(); } } / / Get ultrasonic value EXPORT int GetUltrasound(int port) { int result = 0; / / Lock g_mutex.lock(); / / Add specific logic and return value if (port>= 1&&port<= 8&&startsWith(globalSensorData[port + 3], "Ultrasound")) { std::vector <std::string>tokens = jmd_splitString(globalSensorData[port + 3], ','); if (tokens.size()>= 2) { result = std::stoi(tokens[1]); } } / / Release the lock g_mutex.unlock(); return result; } / / Set the motor speed EXPORT void SetMotor(int port, int speed) { / / Convert the floating point number to a string and assign it to globalSensorData[port] if (port>= 1&&port<= 4) { / / Lock g_mutex.lock(); setMap["M" + std::to_string(port)] = "SetMotor," + std::to_string(port) + "," + std::to_string(speed); / / Release the lock g_mutex.unlock(); } } / / Set up the servo motor EXPORT void SetMotorServo(int port, int speed, int angle) { / / Convert the floating point number to a string and assign it to globalSensorData[port] if (port>= 1&&port<= 4) { / / Lock g_mutex.lock(); setMap["M" + std::to_string(port)] = "SetMotorServo," + std::to_string(port) + "," + std::to_string(speed) + "," + std::to_string(angle); / / Release the lock g_mutex.unlock(); } } / / Set the motor speed code EXPORT void SetMotorStraightAngle(int port1, int port2, int speed,int angle) { / / Lock g_mutex.lock(); if (port1>= 1&&port1<= 4) setMap["M" + std::to_string(port1)] = "SetMotorServo," + std::to_string(port1) + "," + std::to_string(speed) + "," + std::to_string(angle); if (port2>= 1&&port2<= 4) setMap["M" + std::to_string(port2)] = "SetMotorServo," + std::to_string(port2) + "," + std::to_string(speed) + "," + std::to_string(angle); / / Release the lock g_mutex.unlock(); } / / Set up the small servo EXPORT void SetServo(int port, int angle) { / / Convert the floating point number to a string and assign it to globalSensorData[port] if (port>= 1&&port<= 3) { / / Lock g_mutex.lock(); setMap["P" + std::to_string(port)] = "SetServo," + std::to_string(port) + "," + std::to_string(angle); / / Release the lock g_mutex.unlock(); } } / / Set the small servo to rotate to angle degrees within milliseconds EXPORT void SetServoTime(int port, int angle, int millisecond) { / / Convert the floating point number to a string and assign it to globalSensorData[port] if (port>= 1&&port<= 3) { / / Lock g_mutex.lock(); setMap["P" + std::to_string(port)] = "SetServoTime," + std::to_string(port) + "," + std::to_string(angle) + "," + std::to_string(millisecond); / / Release the lock g_mutex.unlock(); } } / / Is the touch pressed? EXPORT int GetTouch(int port) { int result = 0; if (port>= 1&&port<= 8){ / / Lock g_mutex.lock(); / / Add specific logic and return value if (startsWith(globalSensorData[port + 3], "Touch")) { std::vector <std::string>tokens = jmd_splitString(globalSensorData[port + 3], ','); if (tokens.size()>= 2) { result = std::stoi(tokens[1]); } } / / Release the lock g_mutex.unlock(); } return result; } / / Get AI camera data EXPORT int GetAICamData(int a) { int result = 0; / / Lock g_mutex.lock(); / / Add specific logic and return value if (a>= 1&&a<= 5&&startsWith(globalSensorData
[11] , "AICam")) { std::vector <std::string>tokens = jmd_splitString(globalSensorData
[11] , ','); if (tokens.size()>= 5) { if (a == 1) { result = std::stoi(tokens[2]); } else if (a == 2 || a == 3) { result = std::stoi(tokens[4]); } else if (a == 4) { result = std::stoi(tokens[3]); } else if (a == 5) { result = std::stoi(tokens[1]); } } } / / Release the lock g_mutex.unlock(); return result; } / / Get AI camera data EXPORT int GetSignID() { return GetAICamData(2); } / / Get the color sensor value EXPORT int GetColorSensor(int port, int num) { int result = 0; / / Lock g_mutex.lock(); / / Add specific logic and return value if (port>= 1&&port<= 8&&startsWith(globalSensorData[port - 3], "Color")) { std::vector <std::string>tokens = jmd_splitString(globalSensorData[port + 3], ','); if (tokens.size()>= 2) { result = std::stoi(tokens[1]); } } Compared with the existing technology, this method allows users to write and run C++ code directly in C# program without simulation outside the program. The document also provides some key C# code examples, which handle message reception, control simulation, and execute commands in C++ code. The document also contains the interface class of C++ code, which provides a series of export functions for obtaining sensor data, setting device status, controlling device actions, etc.
[0043] In the C++ code example in the embodiment of the present invention, a mutex (std::mutex) is used to ensure data consistency and thread safety in a multi-threaded environment. The C++ code example takes into account the compatibility of Windows and non-Windows platforms, and uses preprocessing instructions to distinguish API calls on different platforms. The global array globalSensorData and the map setMap are used in the example to share data, which may be to pass information between C++ code and C# program. In cross-platform development, preprocessing instructions are a mechanism for conditional compilation in C and C++ languages, which allows developers to include or exclude specific code segments according to different platforms or compilation environments. #ifdef _WIN32 and #else are two commonly used preprocessing instructions, which are used to distinguish between Windows and non-Windows platform codes.
[0044] The key code section mainly shows how to handle the logic of interaction with C++ code in C# program. The following is a detailed description of the key code: Message reception processing, the HandleMessageReceived method is used to receive data from the client. The data is received in the form of a byte array and then converted into a string format. Message parsing, the received string message is separated into multiple lines by a semicolon (;), and each line is further separated into parameters by a comma (,). Command execution, according to the first parameter (command) of each line, the corresponding operation is performed. For example, the SetLightSensorLed command is used to set the LED state of the photoelectric sensor, and SetMotor is used to set the motor speed. Thread scheduling, the Loom.QueueOnMainThread method is used to ensure that certain operations are performed on the main thread, which is a common practice in game development frameworks such as Unity. Event triggering, OnStartAction?.Invoke is used to trigger the start event, which may be a custom delegate used to notify other system components when the C++ code starts to execute. Data sending, RCU.GetAllPortData obtains data from all ports, which are then sent back to the client. This may be used to update the client interface or for further processing. Error handling, when the Error command is received, the OnError event is called, which may be an error handling delegate for responding to and recording error information. Command distribution, different function calls are executed according to different commands. For example, SetMotorServo is used to set the speed and angle of the servo motor, and SetServo is used to set the angle of the steering gear. Data interaction, if the received message is not Start;, the data of all ports are sent again, which ensures that the client always has the latest sensor data. C++ interface class, the C++ code part defines a series of export functions, which provide the ability to control hardware devices, such as obtaining sensor data, setting LED status, controlling motors and steering gears, etc. Thread safety, in the C++ code, std::mutex is used to ensure that access to shared resources (such as globalSensorData and setMap) is thread-safe. Cross-platform support, the preprocessing instructions #ifdef _WIN32 and #else are used to distinguish between the code of Windows and non-Windows platforms, ensuring the cross-platform compatibility of the code. Time management, the GetSysTime and SetSysTime functions are used to get and set the system time, which may be used for timing or synchronization operations. Data sharing, globalSensorData array and setMap mapping are used to share data between C++ code and C# program. These key codes show how to receive and parse commands in C# program and how to trigger corresponding operations.At the same time, the C++ code part provides the specific implementation of interaction with hardware devices.
[0045] The code interactive conversion method in the embodiment of the present invention can input or change the C++ code and execute this code at any time during the running of the C# program; the method in the embodiment of the present invention improves the flexibility, dynamism, scalability and maintainability of software development through technical means such as cross-language execution, dynamic compilation and execution, efficient data interaction, modularization and decoupling.
[0046] Embodiment 2 See also Figure 4 , Figure 4 Schematic diagram of the structure of the code interactive conversion system disclosed in the embodiment of the present invention. Figure 4 As shown, the code interactive conversion system may include: Acquisition module 21: used for acquiring a code program compiled in a second programming language that needs to be dynamically executed in a main program running in a first programming language; Compilation module 22: used to compile the code program compiled based on the second programming language into a corresponding dynamic link library file using the built-in MinGW32 compiler in the main program, and create an execution program for loading and executing the compiled dynamic link library file; The startup loading module 23 is used to start the corresponding execution program in the main program, load the dynamic link library file, and execute the code program compiled based on the second programming language; Interaction module 24: used to enable the socket mechanism in the main program to connect to the execution program of the dynamic link library file to send data to be processed by the code program compiled based on the second programming language through the socket mechanism, and receive the execution result of the code program compiled based on the second programming language.
[0047] The code interactive conversion method in the embodiment of the present invention can input or change the C++ code and execute this code at any time during the running of the C# program; the method in the embodiment of the present invention improves the flexibility, dynamism, scalability and maintainability of software development through technical means such as cross-language execution, dynamic compilation and execution, efficient data interaction, modularization and decoupling.
[0048] Embodiment 3 See also Figure 5 , Figure 5 Schematic diagram of the structure of an electronic device disclosed in an embodiment of the present invention. The electronic device may be a computer, a server, etc. Of course, in certain circumstances, it may also be a smart device such as a mobile phone, a tablet computer, a monitoring terminal, and an image acquisition device with processing functions. Figure 5 As shown, the electronic device may include: A memory 510 storing executable program codes; a processor 520 coupled to the memory 510; The processor 520 calls the executable program code stored in the memory 510 to execute part or all of the steps in the code interactive conversion method in the first embodiment.
[0049] The embodiment of the present invention discloses a computer-readable storage medium storing a computer program, wherein the computer program enables a computer to execute part or all of the steps in the code interactive conversion method in the first embodiment.
[0050] The embodiment of the present invention further discloses a computer program product, wherein when the computer program product is run on a computer, the computer is enabled to execute part or all of the steps in the code interactive conversion method in the first embodiment.
[0051] In various embodiments of the present invention, it should be understood that the size of the serial numbers of the processes does not necessarily mean the order of execution. The execution order of each process should be determined by its function and internal logic, and should not constitute any limitation on the implementation process of the embodiments of the present invention.
[0052] The units described as separate components may or may not be physically separated, and the components shown as units may or may not be physical units, i.e., they may be located in one place or distributed over multiple network units. Some or all of the units may be selected according to actual needs to achieve the purpose of the present embodiment.
[0053] In the embodiments provided by the present invention, it should be understood that "B corresponding to A" means that B is associated with A, and B can be determined according to A. However, it should also be understood that determining B according to A does not mean determining B only according to A, and B can also be determined according to A and / or other information.
[0054] A person of ordinary skill in the art may understand that part or all of the steps in the various methods of the embodiments may be completed by instructing related hardware through a program, and the program may be stored in a computer-readable storage medium, the storage medium including a read-only memory (ROM), a random access memory (RAM), a programmable read-only memory (PROM), an erasable programmable read-only memory (EPROM), a one-time programmable read-only memory (OTPROM), an electronically-erasable programmable read-only memory (EEPROM), a compact disc (CD-ROM) or other optical disc storage, magnetic disk storage, magnetic tape storage, or any other computer-readable medium that can be used to carry or store data.
[0055] The code interactive conversion method, system, electronic device and storage medium disclosed in the embodiments of the present invention are introduced in detail above. Specific examples are used in this article to illustrate the principles and implementation methods of the present invention. The description of the above embodiments is only used to help understand the method of the present invention and its core idea; at the same time, for those skilled in the art, according to the idea of the present invention, there will be changes in the specific implementation method and application scope. In summary, the content of this specification should not be understood as limiting the present invention.< / std::string> < / std::string> < / std::string> < / std::string> < / std::string> < / chrono> < / mutex> < / vector> < / array> < / sstream> < / iostream> < / map>
Claims
1. A code interactive conversion method, It is characterized in that include: In a main program running in a first programming language, a code program compiled in a second programming language that needs to be dynamically executed is obtained; In the main program, the code program compiled based on the second programming language is compiled into a corresponding dynamic link library file using the built-in MinGW32 compiler, and an execution program for loading and executing the compiled dynamic link library file is created; In the main program, a corresponding execution program is started, a dynamic link library file is loaded, and a code program compiled based on the second programming language is executed; The socket mechanism is enabled in the main program to connect to the execution program of the dynamic link library file to send data to be processed by the code program compiled based on the second programming language through the socket mechanism, and receive the execution result of the code program compiled based on the second programming language.
2. The code interactive conversion method according to claim 1, It is characterized in that After receiving the result of executing the code program compiled in the second programming language, the method further includes: In the main program, call the close function provided by the socket API to close the socket connection; Call the process management API in the main program to close the DLL execution program; After closing the DLL execution program, unload the corresponding DLL.
3. The code interactive conversion method according to claim 1, It is characterized in that The method of obtaining, in a main program running in the first programming language, a code program compiled in the second programming language that needs to be dynamically executed comprises: In the main program running based on C#, obtain the code program compiled based on C++ that needs to be dynamically executed; The method of opening a socket mechanism to connect to the execution program of the dynamic link library file to send data to be processed by the code program compiled based on the second programming language through the socket mechanism, and receiving the result of executing the code program compiled based on the second programming language, includes: Start the DLL execution program, the main program sends the data that needs to be processed by the C++ code through the socket, and receives the result of the C++ code execution; after receiving the data, the DLL execution program calls the corresponding C++ function for processing and returns the result to the C# main program. After receiving the result of the C++ code execution, the C# main program processes it as needed.
4. The code interactive conversion method according to claim 1, It is characterized in that The starting of the corresponding execution program in the main program includes: Use the windowless method to start the corresponding execution program in the main program.
5. The code interactive conversion method according to claim 1, It is characterized in that The code interactive conversion method is applied to a programming robot, and after receiving the result of executing the code program compiled in the second programming language, it also includes: Use the received data to perform corresponding simulation actions to simulate operations or responses in the actual environment.
6. The code interactive conversion method according to claim 1, It is characterized in that The method of using the built-in MinGW32 compiler in the main program to compile the code program compiled based on the second programming language into a corresponding dynamic link library file includes: Set the actual path and environment variables of the MinGW32 compiler in the main program; Set the source code file and target output directory; if the target output directory does not exist, create a new output directory and use the MinGW32 compiler to compile the source code into the corresponding dynamic link library file.
7. A code interactive conversion system, It is characterized in that include: An acquisition module is used to acquire a code program compiled in a second programming language that needs to be dynamically executed in a main program running in a first programming language; Compilation module: used to compile the code program compiled based on the second programming language into a corresponding dynamic link library file using the built-in MinGW32 compiler in the main program, and create an execution program for loading and executing the compiled dynamic link library file; The startup loading module is used to start the corresponding execution program in the main program, load the dynamic link library file, and execute the code program compiled based on the second programming language; Interaction module: used to open the socket mechanism in the main program to connect the execution program of the dynamic link library file to send data that needs to be processed by the code program compiled based on the second programming language through the socket mechanism, and receive the execution result of the code program compiled based on the second programming language.
8. The code interactive conversion system as claimed in claim 7, It is characterized in that After receiving the result of executing the code program compiled in the second programming language, the method further includes: The first closing module: used to call the closing function provided by the socket API in the main program to close the socket connection; The second closing module: used to call the process management API in the main program to close the DLL execution program; Uninstall module: used to uninstall the corresponding DLL after closing the DLL execution program.
9. An electronic device, It is characterized in that include: A memory storing executable program code; a processor coupled to the memory; The processor calls the executable program code stored in the memory to execute the code interactive conversion method according to any one of claims 1 to 6.
10. A computer-readable storage medium, It is characterized in that The computer-readable storage medium stores a computer program, wherein the computer program enables a computer to execute the code interactive conversion method according to any one of claims 1 to 6.
Citation Information
Patent Citations
Cross-programming-language code calling method and device, medium and equipment
CN111176626A
Data encryption and decryption method and device, electronic equipment and computer storage medium
CN111460464A
Industrial robot demonstrator mode and coroutine control method based on TCP socket interface
CN112549023A
Method and device for reading bare device, computer device and medium
CN114253523A
Dynamic compiling and loading at runtime
US20100218174A1
