C api to C# GUI

穿精又带淫゛_ 提交于 2019-12-23 02:18:51

问题


I have a stream of bytes that I sort into structs. Now I need to update a C# GUI using values from those structs. Now I've found things about pinvoke and dllimport using Google but everything is calling c code from c#, I need to do the opposite.

The c# code has functions that spin dials/updates values, so once I have the values I need I want to just call those functions, with those values as parameters, my c code is all written and the gui is all coded and functional using dials that I drag with my mouse, I just need to glue these together.

Thanks for any help!


回答1:


Generally speaking, you cannot call C# code from C code. (You can call back into C# code from C code, but the C# side needs to initiate the process and pass in a callback.)

The "right way" is for the C# code to call into the C code and provide a callback function (look up the UnmanagedFunctionPointer attribute for how to turn a managed delegate into a function pointer.)

If that option isn't possible, you have a few alternatives, but none of them are going to be as easy as just "gluing thing together":

  • Use a mixed-mode C++ library to bridge the C and C# code. This is a mess, IMO, and I only suggest it because its the least amount of change to your C code.
  • Expose a COM object from your C# code and communicate with that from C. Slightly less messy than option A but at the cost of introducing COM into the mix.
  • Use some form of inter-process communications (TCP sockets, named pipes, etc.) and communicate between the two code elements as if they were separate programs.



回答2:


How about you call your C code from C# using PInvoke, make the C code return some data, and then have the C# application use that data to update the GUI? Is there some reason you can't have the C# code just be "in charge", only calling the C code when it is needed and otherwise just taking over the UI thread? Why do you want your C code to be able to update the GUI?



来源:https://stackoverflow.com/questions/9271863/c-api-to-c-sharp-gui

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!