A code interactive conversion method and system
By embedding the MinGW32 compiler in a C# program and utilizing the socket mechanism to dynamically load and execute C++ code, the problem of dynamically modifying C++ code in a C# program is solved, improving the flexibility and security of software development.
Patent Information
- Application Number
- CN202411138038.5
- Authority / Receiving Office
- CN · China
- Patent Type
- Patents(China)
- Current Assignee / Owner
- Filing Date
- 2024-08-19
- Publication Date
- 2025-10-31
- Estimated Expiration
- 2044-08-19
AI Technical Summary
In software development, especially in mixed programming (such as interoperability between C# and C++), traditional methods cannot dynamically modify and execute C++ code in a pre-packaged C# program, which presents problems such as high difficulty and high security vulnerability risks.
By embedding the MinGW32 compiler in the C# program, C++ code is compiled into a dynamic link library file, and the socket mechanism is used for data interaction and result transmission, thus realizing the dynamic loading and execution of C++ code.
It enables the input or modification of C++ code at any time during the execution of a C# program, improving the flexibility, dynamism, scalability, and maintainability of software development, while reducing security risks.
Smart Images

Figure CN118760435B_ABST
Abstract
Description
Technical Field
[0001] This invention relates to the field of programming technology, and more specifically to a code interactive conversion method and system. Background Technology
[0002] Currently, in software development, especially when it comes to mixed programming (such as C# and C++ interoperability), dynamically modifying and executing C++ code directly within a pre-packaged C# program is indeed a complex and challenging task. This is mainly because C# and C++ have significant differences in their compilation and runtime behavior, and they typically follow different memory management and compilation models.
[0003] C#, a high-level programming language, runs on the .NET Framework or .NET Core. It uses Just-In-Time (JIT) or Action-Oriented (AOT) compilation to convert source code into Intermediate Language (IL), which is then translated into machine code by the Common Language Runtime (CLR) for execution. C# programs undergo type safety checks and garbage collection during compilation to ensure stability and security. C++, a programming language closer to the hardware, compiles source code directly into machine code during compilation, bypassing intermediate layers. This results in higher execution efficiency for C++ programs, but also requires developers to have a deeper understanding of memory management, pointer manipulation, and other related concepts.
[0004] Once C++ code is compiled into an executable file or DLL, its machine code is fixed and cannot be directly modified unless recompiled. This means that it is impossible to directly modify C++ code in C# and make it effective. C# and C++ programs typically 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 could be found to modify C++ code at runtime, this would introduce serious security vulnerabilities because it compromises the integrity and predictability of the code. Traditional methods cannot directly and dynamically change the execution of C++ code within a packaged C# program. Therefore, designing a scheme that enables code-interactive conversion has become a pressing technical problem for those skilled in the art. Summary of the Invention
[0005] To address the aforementioned shortcomings, this invention discloses a code interaction conversion method that can significantly improve the system's flexibility.
[0006] The first aspect of this invention discloses a code interaction conversion method, including:
[0007] In the main program that runs based on the first programming language, obtain the code program that needs to be dynamically executed and compiled based on the second programming language;
[0008] The main program uses the built-in MinGW32 compiler to compile the code program based on the second programming language into the corresponding dynamic link library file, and creates an executable program to load and execute the compiled dynamic link library file;
[0009] The main program launches the corresponding executable program, loads the dynamic link library file, and executes the code program compiled based on the second programming language.
[0010] In the main program, a socket mechanism is enabled to connect to the executable program of the dynamic link library file. This allows the program to send data that needs to be processed by the code program compiled based on the second programming language, and to receive the results of the code program compiled based on the second programming language.
[0011] As an optional implementation, in a first aspect of the present invention, after receiving the result of executing the code program compiled based on the second programming language, the method further includes:
[0012] In the main program, call the close function provided by the socket API to close the socket connection;
[0013] Call the process management API in the main program to shut down the DLL executor;
[0014] After closing the DLL executor, uninstall the corresponding DLL.
[0015] As an optional implementation, in the first aspect of the present invention, obtaining the code program compiled based on the second programming language that needs to be dynamically executed in the main program running based on the first programming language includes:
[0016] In the main program running in C#, obtain the C++ compiled code program that needs to be dynamically executed;
[0017] The step of enabling the socket mechanism to connect to the executable 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, and to receive the results of the execution of the code program compiled based on the second programming language, includes:
[0018] The DLL executable is started. The main program sends data that needs to be processed by C++ code via a socket and receives the results of the C++ code execution. After receiving the data, the DLL executable calls the corresponding C++ function to process it 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.
[0019] As an optional implementation, in the first aspect of the present invention, starting the corresponding execution program in the main program includes:
[0020] The corresponding executable program is launched in a windowless manner in the main program.
[0021] As an optional implementation, in a first aspect of the present invention, the code interaction 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 further includes:
[0022] Use the received data to perform corresponding simulation actions to simulate operations or responses in a real-world environment.
[0023] As an optional implementation, in the first aspect of the present invention, the step of compiling the code program based on the second programming language into a corresponding dynamic link library file using the built-in MinGW32 compiler in the main program includes:
[0024] Set the actual path and environment variables for the MinGW32 compiler in the main program;
[0025] 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.
[0026] A second aspect of this invention discloses a code-interactive conversion system, comprising:
[0027] Acquisition module: Used to acquire the code program compiled based on the second programming language that needs to be dynamically executed in the main program running based on the first programming language;
[0028] The compilation module is used in the main program to compile the code program based on the second programming language into the corresponding dynamic link library file using the built-in MinGW32 compiler. It creates an executable program in the main program to load and execute the compiled dynamic link library file. The executable program can be dynamically created when compiling C++, or it can be developed when developing the main program. It is preferable that the executable program has been developed when developing the main program.
[0029] Startup Loading Module: Used to launch the corresponding executable program in the main program, load the dynamic link library file, and execute the code program compiled based on the second programming language;
[0030] Interaction module: Used in the main program to enable the socket mechanism to connect to the executable program of the dynamic link library file, so as to send data that needs to be processed by the code program compiled based on the second programming language, and to receive the results of the execution of the code program compiled based on the second programming language.
[0031] As an optional implementation, in a second aspect of the present invention, after receiving the result of executing the code program compiled based on the second programming language, the method further includes:
[0032] The first closing module is used in the main program to call the closing function provided by the socket API to close the socket connection;
[0033] The second shutdown module is used in the main program to call the process management API to shut down the DLL executor.
[0034] Unload module: Used to unload the corresponding DLL after the DLL executor is closed.
[0035] Compared with the prior art, the embodiments of the present invention have the following beneficial effects:
[0036] The code interaction conversion method in this embodiment of the invention enables users to input or modify C++ code and execute it at any time during the execution of a C# program. The method in this embodiment of the invention improves the flexibility, dynamism, scalability and maintainability of software development through cross-language execution, dynamic compilation and execution, efficient data interaction, and modularization and decoupling techniques. Attached Figure Description
[0037] To more clearly illustrate the technical solutions in the embodiments of the present invention, the accompanying drawings used in the embodiments will be briefly introduced below. Obviously, the drawings described below are only some embodiments of the present invention. For those skilled in the art, other drawings can be obtained based on these drawings without creative effort.
[0038] Figure 1 This is a flowchart illustrating the code interaction conversion method disclosed in an embodiment of the present invention;
[0039] Figure 2 This is a flowchart illustrating the steps for closing the uninstallation process as disclosed in an embodiment of the present invention;
[0040] Figure 3 This is a schematic diagram illustrating the specific process of the code interaction conversion method disclosed in this embodiment of the invention.
[0041] Figure 4 This is a schematic diagram of the structure of a code interaction conversion system provided in an embodiment of the present invention;
[0042] Figure 5 This is a schematic diagram of the structure of an electronic device provided in an embodiment of the present invention. Detailed Implementation
[0043] The technical solutions of the embodiments of the present invention will be clearly and completely described below with reference to the accompanying drawings. Obviously, the described embodiments are only some embodiments of the present invention, and not all embodiments. Based on the embodiments of the present invention, all other embodiments obtained by those skilled in the art without creative effort are within the scope of protection of the present invention.
[0044] It should be noted that the terms "first," "second," "third," "fourth," etc., in the specification and claims of this invention are used to distinguish different objects, not to describe a specific order. The terms "comprising" and "having," and any variations thereof, in the embodiments of this invention are intended to cover non-exclusive inclusion. Exemplarily, a process, method, system, product, or device that includes a series of steps or units is not necessarily limited to those steps or units explicitly listed, but may include other steps or units not explicitly listed or inherent to these processes, methods, products, or devices.
[0045] Traditional methods cannot directly modify and execute C++ code within a pre-packaged C# program. This invention discloses a code interaction conversion method, system, electronic device, and storage medium. By using a built-in C++ compiler and developing a subroutine to execute a DLL, C++ code is compiled into a DLL. The subroutine is then launched to load the DLL. The main program communicates with the subroutine via socket to exchange data. After execution, the subroutine is closed. This allows C++ code to be entered or modified and executed at any time during the execution of a C# program.
[0046] Example 1
[0047] Please see Figure 1 , Figure 1 This is a flowchart illustrating the code interaction and conversion method disclosed in this embodiment of the invention. The execution entity of the method described in this embodiment is an execution entity composed of software and / or hardware. This execution entity can receive relevant information via wired or / or wireless means and can send certain instructions. Of course, it can also have certain processing and storage functions. This execution entity can control multiple devices, such as remote physical servers or cloud servers and related software, or it can be a local host or server and related software that performs related operations on devices located in a certain place. In some scenarios, it can also control multiple storage devices, which can be placed in the same location as the devices or in different locations. Figure 1 , Figure 2and Figure 3 As shown, this code-based interactive conversion method includes the following steps:
[0048] S101: In the main program running in the first programming language, obtain the code compiled in the second programming language that needs to be dynamically executed; in the C# main program, a mechanism needs to be provided to obtain C++ code provided by the user or an external system. This can be achieved through text input boxes, file upload interfaces, network requests, or other methods. The obtained C++ code will be stored as a string in memory, awaiting subsequent processing.
[0049] S102: In the main program, use the built-in MinGW32 compiler to compile the code program based on the second programming language into the corresponding dynamic link library file, and create an executable program to load and execute the compiled dynamic link library file; include the relevant executable files and library files of the MinGW32 compiler in the installation directory of the C# program. This way, when C++ code needs to be compiled, the program can directly call these files without the user needing to install a separate compiler. Create a separate program responsible for loading and executing the compiled DLL file. This program can be written in C# or C++ / CLI for easier interoperability with the DLL. Some interfaces need to be defined in this program to receive input from the main program and send output.
[0050] S103: In the main program, launch the corresponding executable 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 C# System.Diagnostics.Process class to call the MinGW32 compiler. The acquired C++ code needs to be passed as input to the compiler, and the output should be specified as a DLL file. During compilation, some compilation options may need to be set, such as optimization level and debug information generation.
[0051] S104: In the main program, establish a socket mechanism to connect to the executable program of the dynamic link library file. This allows the main program to send data that needs to be processed by code compiled in a second programming language and to receive the results of the code compiled in the second programming language. Establish a socket connection between the main program and the DLL executable 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 executable program via the socket and receives the execution results. You need to define a communication protocol to ensure correct data transmission and parsing. Once the C++ code has finished executing and all the necessary data has been transmitted via the socket, the main program needs to close the socket connection. This can be done by calling the Close method of the Socket class. Simultaneously, the main program needs to shut down the DLL executable program, which can be done by calling the Kill method of the Process class. Finally, you can optionally delete the compiled DLL file to clean up resources.
[0052] The method described above enables the execution of code written in a second programming language within 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, thus improving the flexibility and reusability of software development.
[0053] Using the built-in MinGW32 compiler, this method can dynamically compile code in a second programming language into dynamic link library files and create an executable program to load and execute these library files. This dynamic compilation and execution capability allows software to compile and execute new or modified code in real time as needed, enhancing the software's dynamism and scalability.
[0054] This method enables data exchange between the main program and the executable program of the dynamic link library file through a socket mechanism. This mechanism allows the main program to send data to a code program based on a second programming language for processing and receive the processing results, achieving efficient and flexible data exchange and communication.
[0055] By compiling code based on a second programming language into dynamic link library files and communicating via a socket mechanism, this method achieves decoupling and independent deployment of code modules. This allows different modules or components to be developed, tested, and deployed independently, improving software development efficiency and maintainability.
[0056] More preferably, after receiving the result of executing the code program compiled based on the second programming language, the method further includes:
[0057] S105: In the main program, call the close function provided by the socket API 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 leaks can be avoided, and the stability and performance of the system can be ensured.
[0058] S106: Call the process management API in the main program to close the DLL executable; using the process management API to close the DLL executable can ensure that the memory, file handles and other resources occupied by the program are properly released, preventing memory leaks and other resource occupation problems.
[0059] S107: After closing the DLL executor, uninstall the corresponding DLL. Uninstalling the corresponding DLL file after closing the DLL executor can further release resources associated with the DLL, including memory, file handles, etc., ensuring effective management of system resources.
[0060] By promptly closing socket connections, shutting down DLL executables, and unloading DLLs, system crashes or performance degradation caused by excessive resource consumption can be avoided, thereby improving system stability and reliability. Timely release and unloading of unused resources can reduce potential security risks, such as preventing malicious code from exploiting open connections or unloaded DLLs. Explicitly including resource release and unloading logic in the code makes it cleaner, more organized, and easier to maintain and extend.
[0061] More preferably, obtaining the code program compiled based on the second programming language that needs to be dynamically executed in the main program running based on the first programming language includes:
[0062] In the main program running in C#, obtain the C++ compiled code program that needs to be dynamically executed;
[0063] The step of enabling the socket mechanism to connect to the executable 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, and to receive the results of the execution of the code program compiled based on the second programming language, includes:
[0064] The DLL executable is started. The main program sends data that needs to be processed by C++ code via a socket and receives the results of the C++ code execution. After receiving the data, the DLL executable calls the corresponding C++ function to process it 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.
[0065] It allows you to enter or modify C++ code at any time during the execution of a C# program, and execute that code. It combines the ease of use of C# with the high performance of C++, making it suitable for scenarios that require high-performance computing but also want to maintain the ease of use of the program. By dynamically loading DLLs, you can easily extend the functionality of the program without recompiling the entire program. It allows you to take advantage of C++ in the C# environment to achieve cross-language programming and code reuse.
[0066] Since no external process needs to be launched, this approach may offer better performance, especially in scenarios requiring frequent execution of C++ code. Launching and managing external processes consumes additional resources and can introduce performance overhead.
[0067] This approach, handling the process within the main program, offers greater flexibility because it makes it easier to modify and extend how the C++ code executes without changing the external program. If modifications to the C++ code's execution are required, it might necessitate recompiling and redeploying the external program, increasing maintenance complexity.
[0068] Because C++ code executes within the context of the main program, errors that occur during execution are easier to catch, handle, and debug. Error handling and debugging outside the main program can be more difficult due to the need to address cross-process communication and synchronization issues.
[0069] More preferably, starting the corresponding executable program in the main program includes:
[0070] The corresponding executable program is launched in a windowless manner in the main program.
[0071] The windowless launch mode of this invention avoids additional pop-up windows, thus preventing interference with the user's current interface and improving user experience. Not creating additional windows reduces system resource consumption, including memory and CPU resources, which is especially important in resource-constrained environments or for applications requiring high performance. The windowless mode allows the executable to run in the background, which is very useful for applications that need to perform long-running tasks or do not require user interaction. Windowless execution reduces the user's chances of interacting with potential malware, thereby lowering security risks. In the C# main program, the System.Diagnostics.Process class is used to launch the DLL executable. You need to set the CreateNoWindow property of ProcessStartInfo to true to run the program in windowless mode. Simultaneously, the path to the compiled DLL is passed as a parameter to the program.
[0072] More preferably, the code interaction 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 further includes:
[0073] Use the received data to perform corresponding simulation actions to simulate operations or responses in a real-world environment.
[0074] By using code-interactive conversion methods, programming robots can more easily integrate and use code written in different programming languages, thereby increasing their flexibility and scalability. The simulated actions of programming robots in virtual environments can provide more intuitive and easier-to-understand feedback, helping users better understand and use the programming robots.
[0075] More preferably, the step of using the built-in MinGW32 compiler in the main program to compile the code program based on the second programming language into the corresponding dynamic link library file includes:
[0076] Set the actual path and environment variables for the MinGW32 compiler in the main program;
[0077] 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.
[0078] The following key code is disclosed and briefly described in this embodiment of the invention:
[0079] / / 1. The main program receives data and controls the simulation.
[0080] private void HandleMessageReceived(byte[] data, NetworkStreamclientStream)
[0081] {
[0082] / / Logic for processing received messages
[0083] string msg = Encoding.UTF8.GetString(data);
[0084] string[] line = msg.Split(';');
[0085] / / UnityEngine.Debug.Log(CarHJ.GetInstance().rcuTime + "" + msg);
[0086] if (runStart)
[0087] {
[0088] runStart = false;
[0089] Loom.QueueOnMainThread(() =>
[0090] {
[0091] OnStartAction?.Invoke("");
[0092] string rdata = RCU.GetAllPortData();
[0093] / / UnityEngine.Debug.Log("ready send: " + rdata);
[0094] byte[] d = Encoding.UTF8.GetBytes(rdata);
[0095] SocketServerUtility.SendData(d, clientStream);
[0096] });
[0097] }
[0098] if (line.Length>0)
[0099] {
[0100] foreach (var item in line)
[0101] {
[0102] string[] cmd = item.Split(',');
[0103] if (cmd.Length>0)
[0104] {
[0105] switch (cmd[0])
[0106] {
[0107] case "SetLightSensorLed":
[0108] RCU.SetLightSensorLed(int.Parse(cmd[1]), int.Parse(cmd[2]));
[0109] break;
[0110] case "SetMotor":
[0111] RCU.SetMotor(int.Parse(cmd[1]), int.Parse(cmd[2]));
[0112] break;
[0113] case "SetMotorServo":
[0114] RCU.SetMotorServo(int.Parse(cmd[1]), int.Parse(cmd[2]), int.Parse(cmd[3]));
[0115] break;
[0116] case "SetMotorStraightAngle":
[0117] RCU.SetMotorStraightAngle(int.Parse(cmd[1]), int.Parse(cmd[2]),int.Parse(cmd[3]), int.Parse(cmd[4]));
[0118] break;
[0119] case "SetServo":
[0120] RCU.SetServo(int.Parse(cmd[1]), int.Parse(cmd[2]));
[0121] break;
[0122] case "SetServoTime":
[0123] RCU.SetServoTime(int.Parse(cmd[1]), int.Parse(cmd[2]), int.Parse(cmd[3]));
[0124] break;
[0125] case "Set3CLed":
[0126] RCU.Set3CLed(int.Parse(cmd[1]), int.Parse(cmd[2]));
[0127] break;
[0128] case "SetMp3Play":
[0129] RCU.SetMp3Play(int.Parse(cmd[1]));
[0130] break;
[0131] case "SetMp3Suspend":
[0132] RCU.SetMp3Suspend();
[0133] break;
[0134] case "SetInBeep":
[0135] RCU.SetInBeep(int.Parse(cmd[1]));
[0136] break;
[0137] case "SetLizard":
[0138] RCU.SetLizard(int.Parse(cmd[1]));
[0139] break;
[0140] case "UpdateVar":
[0141] RCU.ShowVar(cmd[1], cmd[2]);
[0142] break;
[0143] case "Error":
[0144] Loom.QueueOnMainThread(() =>
[0145] {
[0146] OnError?.Invoke("RunError," + item.Replace("Error,", ""));
[0147] });
[0148] break;
[0149] }
[0150] }
[0151] }
[0152] if (!msg.Equals("Start;"))
[0153] {
[0154] string rdata = RCU.GetAllPortData();
[0155] / / UnityEngine.Debug.Log("ready send: " + rdata);
[0156] byte[] d = Encoding.UTF8.GetBytes(rdata);
[0157] SocketServerUtility.SendData(d, clientStream);
[0158] }
[0159] }
[0160] }
[0161] / / 2.C++ interface class:
[0162] #include "jmd.h"
[0163] #include "utils.h"
[0164] #include <map>
[0165] #include<stddef.h>
[0166] #include<string.h>
[0167] #include<stdio.h>
[0168] #include<stdlib.h>
[0169] #include <iostream>
[0170] #include <sstream>
[0171] #include <array>
[0172] #include <vector>
[0173] #include <mutex>
[0174] #include <chrono>
[0175] #include<time.h>
[0176] #ifdef _WIN32
[0177] #include<windows.h>
[0178] #else
[0179] #include<unistd.h>
[0180] #endif / / _WIN32
[0181] / / Record the current time (in milliseconds)
[0182] std::chrono::time_point<std::chrono::high_resolution_clock> sysTime;
[0183] / *
[0184] Get controller time and time it in C++
[0185] /
[0186] EXPORT long GetSysTime()
[0187] {
[0188] std::chrono::duration<double, std::milli> a = std::chrono::high_resolution_clock::now() - sysTime;
[0189] / / printf("a:%d\nsysTime:%d\n", a.count, sysTime);
[0190] return a.count();
[0191] }
[0192] / / Reset controller time to zero
[0193] EXPORT void SetSysTime()
[0194] {
[0195] sysTime = std::chrono::high_resolution_clock::now();
[0196] }
[0197] / / / <summary>
[0198] / / / Return to Optoelectronics 0-4095
[0199] / / / < / summary>
[0200] / / / <param name="port">
[0201] / / / <returns>< / returns>
[0202] EXPORT int GetLightSensor(int port)
[0203] {
[0204] int result = 0;
[0205] / / Convert the floating-point number to a string and assign it to globalSensorData[port]
[0206] if (port>= 1&&port<= 8)
[0207] {
[0208] / / Lock
[0209] g_mutex.lock();
[0210] std::string inputString = globalSensorData[port + 3];
[0211] std::vector <std::string>tokens = jmd_splitString(globalSensorData[port + 3], ',');
[0212] if (tokens.size()>= 2&&tokens[0] == "Light")
[0213] {
[0214] result = std::stoi(tokens[1]);
[0215] }
[0216] / / Release lock
[0217] g_mutex.unlock();
[0218] }
[0219] return result;
[0220] }
[0221] / / / <summary>
[0222] / / / Returns to photoelectric 0 or 1, black 1, white 0
[0223] / / / < / summary>
[0224] / / / <param name="port">
[0225] / / / <returns>< / returns>
[0226] EXPORT int GetLightSensorData(int port)
[0227] {
[0228] int grayscale = GetLightSensor(port);
[0229] return grayscale>1474 ? 0 : 1;
[0230] }
[0231] / / Set the photoelectric light switch
[0232] EXPORT void SetLightSensorLed(int port, int state)
[0233] {
[0234] / / Add the function that sets the data to another string.
[0235] if (port>= 1&&port<= 8)
[0236] {
[0237] / / Lock
[0238] g_mutex.lock();
[0239] setMap["P" + std::to_string(port)] = "SetLightSensorLed," + std::to_string(port) + "," + std::to_string(state);
[0240] / / Release lock
[0241] g_mutex.unlock();
[0242] }
[0243] }
[0244] / / Get ultrasound values
[0245] EXPORT int GetUltrasound(int port)
[0246] {
[0247] int result = 0;
[0248] / / Lock
[0249] g_mutex.lock();
[0250] / / Add specific logic and return value
[0251] if (port>= 1&&port<= 8&&startsWith(globalSensorData[port + 3], "Ultrasound"))
[0252] {
[0253] std::vector <std::string>tokens = jmd_splitString(globalSensorData[port + 3], ',');
[0254] if (tokens.size()>= 2)
[0255] {
[0256] result = std::stoi(tokens[1]);
[0257] }
[0258] }
[0259] / / Release lock
[0260] g_mutex.unlock();
[0261] return result;
[0262] }
[0263] / / Set motor speed
[0264] EXPORT void SetMotor(int port, int speed)
[0265] {
[0266] / / Convert the floating-point number to a string and assign it to globalSensorData[port]
[0267] if (port>= 1&&port<= 4)
[0268] {
[0269] / / Lock
[0270] g_mutex.lock();
[0271] setMap["M" + std::to_string(port)] = "SetMotor," + std::to_string(port) + "," + std::to_string(speed);
[0272] / / Release lock
[0273] g_mutex.unlock();
[0274] }
[0275] }
[0276] / / Configure servo motors
[0277] EXPORT void SetMotorServo(int port, int speed, int angle)
[0278] {
[0279] / / Convert the floating-point number to a string and assign it to globalSensorData[port]
[0280] if (port>= 1&&port<= 4)
[0281] {
[0282] / / Lock
[0283] g_mutex.lock();
[0284] setMap["M" + std::to_string(port)] = "SetMotorServo," + std::to_string(port) + "," + std::to_string(speed) + "," + std::to_string(angle);
[0285] / / Release lock
[0286] g_mutex.unlock();
[0287] }
[0288] }
[0289] / / Set motor speed encoding
[0290] EXPORT void SetMotorStraightAngle(int port1, int port2, int speed,int angle)
[0291] {
[0292] / / Lock
[0293] g_mutex.lock();
[0294] if (port1>= 1&&port1<= 4)
[0295] setMap["M" + std::to_string(port1)] = "SetMotorServo," + std::to_string(port1) + "," + std::to_string(speed) + "," + std::to_string(angle);
[0296] if (port2>= 1&&port2<= 4)
[0297] setMap["M" + std::to_string(port2)] = "SetMotorServo," + std::to_string(port2) + "," + std::to_string(speed) + "," + std::to_string(angle);
[0298] / / Release lock
[0299] g_mutex.unlock();
[0300] }
[0301] / / Set up the small servo
[0302] EXPORT void SetServo(int port, int angle)
[0303] {
[0304] / / Convert the floating-point number to a string and assign it to globalSensorData[port]
[0305] if (port>= 1&&port<= 3)
[0306] {
[0307] / / Lock
[0308] g_mutex.lock();
[0309] setMap["P" + std::to_string(port)] = "SetServo," + std::to_string(port) + "," + std::to_string(angle);
[0310] / / Release lock
[0311] g_mutex.unlock();
[0312] }
[0313] }
[0314] / / Set the servo motor to rotate to angle within milliseconds.
[0315] EXPORT void SetServoTime(int port, int angle, int millisecond)
[0316] {
[0317] / / Convert the floating-point number to a string and assign it to globalSensorData[port]
[0318] if (port>= 1&&port<= 3)
[0319] {
[0320] / / Lock
[0321] g_mutex.lock();
[0322] setMap["P" + std::to_string(port)] = "SetServoTime," + std::to_string(port) + "," + std::to_string(angle) + "," + std::to_string(millisecond);
[0323] / / Release lock
[0324] g_mutex.unlock();
[0325] }
[0326] }
[0327] / / Touch was pressed?
[0328] EXPORT int GetTouch(int port)
[0329] {
[0330] int result = 0;
[0331] if (port>= 1&&port<= 8){
[0332] / / Lock
[0333] g_mutex.lock();
[0334] / / Add specific logic and return value
[0335] if (startsWith(globalSensorData[port + 3], "Touch"))
[0336] {
[0337] std::vector <std::string>tokens = jmd_splitString(globalSensorData[port + 3], ',');
[0338] if (tokens.size()>= 2)
[0339] {
[0340] result = std::stoi(tokens[1]);
[0341] }
[0342] }
[0343] / / Release lock
[0344] g_mutex.unlock();
[0345] }
[0346] return result;
[0347] }
[0348] / / Get AI camera data
[0349] EXPORT int GetAICamData(int a)
[0350] {
[0351] int result = 0;
[0352] / / Lock
[0353] g_mutex.lock();
[0354] / / Add specific logic and return value
[0355] if (a>= 1&&a<= 5&&startsWith(globalSensorData
[11] , "AICam"))
[0356] {
[0357] std::vector <std::string>tokens = jmd_splitString(globalSensorData
[11] , ',');
[0358] if (tokens.size()>= 5)
[0359] {
[0360] if (a == 1)
[0361] {
[0362] result = std::stoi(tokens[2]);
[0363] }
[0364] else if (a == 2 || a == 3)
[0365] {
[0366] result = std::stoi(tokens[4]);
[0367] }
[0368] else if (a == 4)
[0369] {
[0370] result = std::stoi(tokens[3]);
[0371] }
[0372] else if (a == 5)
[0373] {
[0374] result = std::stoi(tokens[1]);
[0375] }
[0376] }
[0377] }
[0378] / / Release lock
[0379] g_mutex.unlock();
[0380] return result;
[0381] }
[0382] / / Get AI camera data
[0383] EXPORT int GetSignID()
[0384] {
[0385] return GetAICamData(2);
[0386] }
[0387] / / Get color sensor values
[0388] EXPORT int GetColorSensor(int port, int num)
[0389] {
[0390] int result = 0;
[0391] / / Lock
[0392] g_mutex.lock();
[0393] / / Add specific logic and return value
[0394] if (port>= 1&&port<= 8&&startsWith(globalSensorData[port - 3], "Color"))
[0395] {
[0396] std::vector <std::string>tokens = jmd_splitString(globalSensorData[port + 3], ',');
[0397] if (tokens.size()>= 2)
[0398] {
[0399] result = std::stoi(tokens[1]);
[0400] }
[0401] }
[0402] Compared to existing technologies, this method allows users to directly write and run C++ code within C# programs without needing to perform simulations outside the program. The documentation also provides key C# code examples that handle message reception, simulation control, and execution of commands in C++ code. The documentation further includes an interface class for C++ code, providing a series of exported functions for acquiring sensor data, setting device states, and controlling device actions.
[0403] In the C++ code example of this invention, a mutex (std::mutex) is used to ensure data consistency and thread safety in a multi-threaded environment. The C++ code example considers compatibility with both Windows and non-Windows platforms, using preprocessor directives to differentiate API calls across platforms. The example uses a global array `globalSensorData` and a map `setMap` to share data, likely for passing information between C++ code and the C# program. In cross-platform development, preprocessor directives are a mechanism in C and C++ used for conditional compilation, allowing developers to include or exclude specific code segments based on different platforms or compilation environments. `#ifdef _WIN32` and `#else` are two commonly used preprocessor directives used to differentiate between Windows and non-Windows platform code.
[0404] The key code section primarily demonstrates how to handle the logic of interaction with C++ code within a C# program. The following is a detailed description of the key code: Message reception and processing: The `HandleMessageReceived` method receives data from the client. The data is received as a byte array and then converted to a string format. Message parsing: The received string message is split into multiple lines using semicolons (;), and each line is further separated into parameters using commas (,). Command execution: Based on the first parameter (command) of each line, the corresponding operation is executed. For example, the `SetLightSensorLed` command sets the LED state of the photoelectric sensor, and `SetMotor` sets the motor speed. Thread scheduling: The `Loom.QueueOnMainThread` method ensures that certain operations are executed on the main thread, a common practice in game development frameworks like Unity. Event triggering: `OnStartAction?.Invoke` triggers a start event, which may be a custom delegate used to notify other system components when C++ code execution begins. Data transmission: `RCU.GetAllPortData` retrieves data from all ports, and this data is then sent back to the client. This may be used to update the client interface or for further processing. Error handling: When an Error command is received, the OnError event is invoked. This may be an error handling delegate used to respond to and log error information. Command dispatch: Different function calls are executed depending on the command. 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 servo motor. Data interaction: If the received message is not Start;, data from all ports is resent, ensuring that the client always has the latest sensor data. C++ interface classes: The C++ code defines a series of exported functions that provide control over the hardware device, such as acquiring sensor data, setting LED states, and controlling motors and servos. Thread safety: In the C++ code, std::mutex is used to ensure thread-safe access to shared resources (such as globalSensorData and setMap). Cross-platform support: The preprocessor directives #ifdef _WIN32 and #else are used to distinguish between Windows and non-Windows platforms, ensuring cross-platform compatibility. 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, the globalSensorData array, and the setMap map are used to share data between C++ code and C# programs. These key code snippets demonstrate how commands are received and parsed in a C# program, and how corresponding operations are triggered.Meanwhile, the C++ code provides the specific implementation for interacting with the hardware device.
[0405] The code interaction conversion method in this embodiment of the invention enables users to input or modify C++ code and execute it at any time during the execution of a C# program. The method in this embodiment of the invention improves the flexibility, dynamism, scalability and maintainability of software development through cross-language execution, dynamic compilation and execution, efficient data interaction, and modularization and decoupling techniques.
[0406] Example 2
[0407] Please see Figure 4 , Figure 4 This is a schematic diagram of the structure of the code interaction conversion system disclosed in an embodiment of the present invention. For example... Figure 4 As shown, the code interactive conversion system may include:
[0408] Acquisition Module 21: Used to acquire the code program compiled based on the second programming language that needs to be dynamically executed in the main program running based on the first programming language;
[0409] Compiler Module 22: Used in the main program to compile the code program based on the second programming language into the corresponding dynamic link library file using the built-in MinGW32 compiler, and to create an executable program for loading and executing the compiled dynamic link library file;
[0410] Startup loading module 23: Used to start the corresponding executable program in the main program, load the dynamic link library file, and execute the code program compiled based on the second programming language in it;
[0411] Interaction Module 24: Used in the main program to enable the socket mechanism to connect to the executable program of the dynamic link library file, so as to send data that needs to be processed by the code program compiled based on the second programming language, and to receive the results of the execution of the code program compiled based on the second programming language.
[0412] The code interaction conversion method in this embodiment of the invention enables users to input or modify C++ code and execute it at any time during the execution of a C# program. The method in this embodiment of the invention improves the flexibility, dynamism, scalability and maintainability of software development through cross-language execution, dynamic compilation and execution, efficient data interaction, and modularization and decoupling techniques.
[0413] Example 3
[0414] Please see Figure 5 , Figure 5 This is a schematic diagram of the structure of an electronic device disclosed in an embodiment of the present invention. The electronic device can be a computer, a server, etc. Of course, in certain cases, it can also be a mobile phone, tablet computer, monitoring terminal, or other smart device, as well as an image acquisition device with processing capabilities. Figure 5 As shown, the electronic device may include:
[0415] Memory 510 storing executable program code;
[0416] Processor 520 coupled to memory 510;
[0417] In this process, the processor 520 calls the executable program code stored in the memory 510 to execute some or all of the steps in the code interaction conversion method in Embodiment 1.
[0418] This invention discloses a computer-readable storage medium storing a computer program that causes a computer to perform some or all of the steps in the code interaction conversion method of Embodiment 1.
[0419] This invention also discloses a computer program product, wherein when the computer program product is run on a computer, the computer performs some or all of the steps in the code interaction conversion method in Embodiment 1.
[0420] In various embodiments of the present invention, it should be understood that the sequence number of each process does not necessarily imply 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.
[0421] The units described as separate components may or may not be physically separate. The components shown as units may or may not be physical units; they can be located in one place or distributed across multiple network units. Some or all of the units can be selected to achieve the purpose of this embodiment according to actual needs.
[0422] In the embodiments provided by this invention, it should be understood that "B corresponding to A" means that B is associated with A, and B can be determined based on A. However, it should also be understood that determining B based on A does not mean that B is determined solely based on A; B can also be determined based on A and / or other information.
[0423] Those skilled in the art will understand that some or all of the steps in the various methods of the embodiments described can be implemented by a program instructing related hardware. This program can be stored in a computer-readable storage medium, including read-only memory (ROM), random access memory (RAM), programmable read-only memory (PROM), erasable programmable read-only memory (EPROM), one-time programmable read-only memory (OTPROM), electrically-Erasable Programmable Read-Only Memory (EEPROM), compact disc read-only memory (CD-ROM) or other optical disc storage, disk storage, magnetic tape storage, or any other computer-readable medium capable of carrying or storing data.
[0424] The code interaction conversion method, system, electronic device, and storage medium disclosed in the embodiments of the present invention have been described in detail above. Specific examples have been used to illustrate the principles and implementation methods of the present invention. The descriptions of the above embodiments are only for the purpose of helping to understand the method and core ideas of the present invention. At the same time, for those skilled in the art, there will be changes in the specific implementation methods and application scope based on the ideas of the present invention. Therefore, the content of this specification should not be construed as a limitation of 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, characterized in that, The code interaction conversion method is applied to programming robots, including: In the main program running in the first programming language, code compiled in the second programming language that needs to be dynamically executed is obtained; the process of obtaining the code compiled in the second programming language that needs to be dynamically executed in the main program running in the first programming language includes: In the main program running in C#, obtain the C++ compiled code program that needs to be dynamically executed; The main program uses the built-in MinGW32 compiler to compile the code program based on the second programming language into the corresponding dynamic link library file, and creates an executable program for loading and executing the compiled dynamic link library file; the process of compiling the code program based on the second programming language into the corresponding dynamic link library file using the built-in MinGW32 compiler in the main program includes: Set the actual path and environment variables for 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; The main program launches the corresponding executable program, loads the dynamic link library file, and executes the code program compiled based on the second programming language. In the main program, a socket mechanism is enabled to connect to the executable program of the dynamic link library file. This allows for the transmission of data that needs to be processed by code compiled from a second programming language, and the reception of the results from the execution of the code compiled from the second programming language. The process of enabling the socket mechanism to connect to the executable program of the dynamic link library file, and to transmit data that needs to be processed by code compiled from a second programming language, and to receive the results from the execution of the code compiled from the second programming language, includes: The DLL executable is started. The main program sends data that needs to be processed by C++ code via a socket and receives the results of the C++ code execution. After receiving the data, the DLL executable calls the corresponding C++ function to process it 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. 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 shut down the DLL executor; After closing the DLL executor, uninstall the corresponding DLL; After receiving the result of executing the code program compiled based on the second programming language, the method further includes: Use the received data to perform corresponding simulation actions to simulate operations or responses in a real-world environment.
2. The code interaction conversion method as described in claim 1, characterized in that, The step of starting the corresponding execution program in the main program includes: The corresponding executable program is launched in a windowless manner in the main program.
3. A code interactive conversion system, characterized in that, The code interaction and conversion system is applied to programming robots and includes: Acquisition module: used to acquire, within the main program running in the first programming language, code compiled in the second programming language that needs to be dynamically executed; the acquisition of the code compiled in the second programming language that needs to be dynamically executed within the main program running in the first programming language includes: In the main program running in C#, obtain the C++ compiled code program that needs to be dynamically executed; The compilation module is used in the main program to compile the code program based on the second programming language into the corresponding dynamic link library file using the built-in MinGW32 compiler, and to create an executable program for loading and executing the compiled dynamic link library file; the process of compiling the code program based on the second programming language into the corresponding dynamic link library file using the built-in MinGW32 compiler in the main program includes: Set the actual path and environment variables for 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; Startup Loading Module: Used to launch the corresponding executable 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 in the main program to enable a socket mechanism to connect to the executable program of the dynamic link library file, so as to send data that needs to be processed by the code program compiled based on the second programming language via the socket mechanism, and to receive the results of the execution of the code program compiled based on the second programming language; the process of enabling a socket mechanism to connect to the executable 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 via the socket mechanism, and to receive the results of the execution of the code program compiled based on the second programming language includes: The DLL executable is started. The main program sends data that needs to be processed by C++ code via a socket and receives the results of the C++ code execution. After receiving the data, the DLL executable calls the corresponding C++ function to process it 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. The first closing module is used in the main program to call the closing function provided by the socket API to close the socket connection; The second shutdown module is used in the main program to call the process management API to shut down the DLL executor. Unload module: Used to unload the corresponding DLL after the DLL executor is closed; After receiving the result of executing the code program compiled based on the second programming language, the method further includes: Use the received data to perform corresponding simulation actions to simulate operations or responses in a real-world environment.
4. An electronic device, characterized in that, include: Memory containing executable program code; A processor coupled to the memory; The processor calls the executable program code stored in the memory to execute the code interaction conversion method according to any one of claims 1 to 2.
5. A computer-readable storage medium, characterized in that, The computer-readable storage medium stores a computer program, wherein the computer program causes a computer to perform the code interaction conversion method according to any one of claims 1 to 2.
Citation Information
Patent Citations
Cross-programming-language code calling method and device, medium and equipment
CN111176626A
Method and device for reading bare device, computer device and medium
CN114253523A