Using Python to Access Methods From C# Library - Interop .dll File - c#

I have a .dll file (with "Interop." prefix) containing a library written in C#. Within the library is a class, several enums, several interfaces, and several delgates. (Observed by decompiling the .dll with JetBrains dotPeek)
See the dll structure here:
I need to use pure Python to access the methods within the class. I have tried:
from ctypes import *
name = "Interop.HTBRAILLEDRIVERSERVERLib.dll"
mydll = cdll.LoadLibrary(name)
However attempting to call any of the methods contained in the class "HtBrailleDriverClass" leads to "AttributeError: function 'initialize' not found". I have also attempted to access them from their ordinal indexes:
print mydll[1]
However this gives the error "AttributeError: function ordinal 1 not found".
Is anyone able to shed light on why I am unable to access the class within this .dll and why I cannot access any of the methods either?
Please bear in mind I must use pure Python.

You can use python.net to access it
import clr,sys
sys.path.append("path of your dll")
clr.AddReference("YourDllName")
import YourDllName
Then Try printing any value of member of your class like
print YourDllName.ClassName.Member
from your python script
Note : Your need to put clr.pyd and python.runtime.dll inside your
Python27/Dlls folder
If You don't want to append your dll path then put the dll inside the python2.x/Lib/site-packages folder .
Then u can avoid 2nd line - sys.path.append() too .

Related

Unable to load a COM visible dll within a PHP based webpage as a COM object

Here's what I've done so far:
I wrote a little C# class library to run GET requests to a REST API.
I compiled it, made sure that it worked within another c# application before trying to import this thing into my webpage. Pulled what I wanted to, worked like a charm whilst operating within another c# console app.
I followed this guide to make sure my dll was COM interoperable and reachable:
http://timheuer.com/blog/archive/2007/03/10/14009.aspx
Now, I was given this PHP webpage by someone else, and while I am not an expert in PHP, from what I've gathered it doesn't take much to be.
The only real important stuff is here:
function APIGet($url) {
$object = new COM("API_Call.ApiCaller");
$result = $object->cURLGET($token, $url);
return $result;
}
I wrote that into my function file, which has many other functions that work just fine on the page. The dll contains the namespace API_Call and a public static class, ApiCaller, as well as some other classes that aren't used here.
So then I go to call it on the actual page itself here:
$output = APIGet($apicall);
echo $output;
From which I get this error (edited for readability):
Fatal error: Uncaught com_exception: Failed to create COM object `API_Call.ApiCall':
Invalid syntax in C:\xampp\htdocs\canvasAPI.php:32
Stack trace: #0 C:\xampp\htdocs\canvasAPI.php(32):
com->com('API_Call.ApiCal...') #1 C:\xampp\htdocs\CAForm.php(169):
APIGet('api/v1/courses') #2 {main} thrown in C:\xampp\htdocs\canvasAPI.php on line 32
I have my file, canvasAPI.php with all my functions in it and then the CAForm.php file is the form itself. I've searched high and low for an answer here, but everything either says make the class library COM visible and interoperable, or to enable [COM] com.allow_dcom in php.ini, both of which I already did.
For anyone googling this, I just ended up using C# the whole way. I didn't see a point in continuing down the path of messing with custom COM objects in PHP.

Find path to active user directory in C

I'm writing a C# program where I have to write some files to a temp folder. In this program, I call an executable from a C project which also needs to write to said temp folder. In C#, I can simply find this with
Directory.GetTempPath();
But in C, I can't seem to find any way of locating it. Do I need to rewrite the C program to take the path as an argument? I would really prefer not to since I'm not very proficient in the language and only barely got it working for my current purpose.
Are there any other, static locations in Windows where it would be appropriate to write temporary files?
My suggestion is to declare the file name relative to a system variable, like %temp% and create there your file as standard file (maybe with a pattern so you can delete it at end of your need), there's also F* tempfile() library function, but I used it only on linux and don't know if it works on windows (it returns you a pointer to a system-defined temp file)
There is a similar function GetTempPath in Win32 API - GetTempPathA MSDN link
You can see how most of C# code is implemented using ReferenceSource. For the GetTempPath() function it calls Win32 API directly.

Access C# variable in js script

In the past I've accessed variables from other java scripts by doing
static var somevar;
In one script. And in the other:
OtherScript.somevar;
But I need to access a variable from C# code in a js script. I've tried:
Public static bool somevar;
In the C# file and in the js file:
OtherScript.somevar;
But I get the error: Unknown identifier 'somevar' in the js file
Just put your Unityscript file in the Plugin or in the Standard Assets folders.
Explanation:
In the "standard" way, you can only access a Unityscript variable from a C# script, but you cannot do the opposite. That's just C# code is compiled before Unityscript's one.
So, in order to achieve what you are trying to do, you must move your Unityscript file into a "special" folder (in Unity, they are the Plugin and the Standard Assets ones), so that it would be compiled at first.
After that, you should achieve the access with the usual logic.
You can't call a Static Object from JS and call its properties. You would have to get help from Unity GameObject to get the Object as Component as everything is an ObjectComponent in Unity. Then use that Component(Technically the Script) as your reference.
Example
GameObject name is "MyCsharpGameObject" <- the GameObject that has the Script
Then use.
theCscharpscript : OtherScript;
theCsharpscript = GameObject.find("MyCsharpGameObject").GetComponent("OtherScript");
On usage from the JS
theCsharpscript.thevariable;
Remember when using JS in MonoDevelop it doesn't give you Intellisence and that is just Normal. You can't however access a Static "Class" that is not attached to a GameObject.
if you insist on doing so. Then check Andrea's Answer. But his explanation might be complicated for you to work on.
But summing up the point that he was saying is. C# works in a NameSpace and JS is not part of that NameSpace so at lease you will have to somewhat include it in, and NameSpace is nothing more than a Folder Location in an Project. Simple as that.
However you must always remember to use PragmaStrict in this as it will always be transformed into a MonoDevelop calls even though you did not Extend from it.
Hope this help you.

How to call a class from another drive

I have created a formula for my application. I know that there are many decompilers to break my application, I want to call a class file from my server and save it in my destination path like C:\test\Formula.cs and call it from my exe file where it is located from
C:\Users\Administrator\Documents\Visual Studio 2008\Projects\WindowsFormsApplication8\WindowsFormsApplication8\bin\Debug\myApp.exe
Similarly, since you can read a text file like this:
StreamReader reader = new StreamReader("C:\\test.txt");
I want to read my class like this:
Class readerclass = new Class("C:\\test\\Formula.cs");
Any help is appreciated.
You can't do that. C# is a compiled language! You can't just pull the source down and try to run it. To do this you would have to compile it on-the-fly and read in the resulting assembly, etc. It would be a disaster.
Now if you had compiled assemblies hosted on the server, you could theoretically download them, load them with Assembly.LoadFrom() and then instantiate classes from that.
You have to either create a library project that contains the formula.cs (dll) or include/add this formula.cs file into your current project.

C# or other .NET equivalents of core python modules for IronPython?

I would like to compile and distribute (on .net) some python programs that work well with IronPython, but I am new to .net and am getting errors related to particular python modules. There is a utility for compiling to low level .net and it works well, but I get errors when dealing with common libraries; code that runs in the interpreter does not necessarily compile. For example, the below takes advantage of the basic modules shutil, getpass, and os. getpass.getuser() returns a username as a string. shutil provides, among other things, a copy function (although that one I can rewrite in pure python and get to compile), and os is used here for getting folder info, making dirs and unlinking files. How might I adapt stuff along the following lines, in whole or any part, to use only libraries native to .net? If anyone has used IronPython as a bridge from python to learning .net any related tips are appreciated.
import shutil
import os
import getpass
uname = getpass.getuser()
folders = ["/users/"+uname+"/location", "/users/"+uname+"/other_location"]
for folder in folders:
for root, dir, files in os.walk(folder):
for file in files:
file_name = os.path.join(root, file)
time_stamp = os.stat(file_name).st_mtime
time_dict[time_stamp] = file_name
working_list.append(time_stamp)
def sync_up():
for item in working_list:
if item not in update_list:
os.remove(item)
else:
shutil.copy2(item, some_other_folder)
def cp_function(target=some_folder):
if os.path.exists(target):
sync_up()
else:
try:
os.mkdir(target)
sync_up()
except:
print """error connecting
"""
The os (and shutil ) replacements in .NET are in the System.IO namespace.
The System.IO namespace contains types that allow reading and writing to files and data streams, and types that provide basic file and directory support.
For most of your file file operations, try the methods of the System.IO.File class.
Directory information is available via the System.IO.Directory class.
I'm not aware of a native os.walk alternative, try using the GetDirectories and GetFiles methods to construct your own directory walker. There is an example RecursiveFileProcessor in the Directory.GetDirectories(String) doc.
A simple way to retrieve the user name of the person who is currently logged on, could be the System.Environment.UserName property.
A simple interactive IronPython example:
>>> import clr
>>> from System import Environment
>>> Environment.UserName
'gimel'
>>> from System import IO
>>> IO.Directory.GetCreationTimeUtc('c:/')
<System.DateTime object at 0x000000000000002B [02/07/2006 12:53:25]>
>>> IO.Directory.GetLastWriteTimeUtc('c:/')
<System.DateTime object at 0x000000000000002C [09/11/2009 08:15:32]>
>>> IO.Directory.GetDirectories('C:/').Count
24
>>> help(IO.File.Copy)
Help on built-in function Copy:
Copy(...)
Copy(str sourceFileName, str destFileName, bool overwrite)
Copies an existing file to a new file.
Overwriting a file of the same name is allowed.
...
For the os module you can use the nt module which provides some of the same functions as os including stat, remove, and mkdir. (It also includes others like environ, getcwd, chdir,and popen.)
For example:
» import nt
» nt.getcwd()
'C:\\Program Files\\Microsoft Visual Studio 10.0\\Common7\\IDE'
However, the implementation is incomplete so, unfortunately, it does not have path or walk. For those, you might need to use .NET's System.IO as gimel suggests.

Categories