PInvoke Issues...

G

Guest

Hi,

I want to programmatically open a service and tune it's configuration from
C#. I think I'm having PInvoke issues because I imported the service API
functions and I'm getting nonsense errors from GetLastError() {RPC server not
found/file volume label incorrect} when I try to open the SCM database. I'm
trying to open it on my local machine and I am an Administrator... Questions:

Here's the WIN32 API signature that I'm getting nonsense errors from:

SC_HANDLE OpenSCManager(
LPCTSTR lpMachineName,
LPCTSTR lpDatabaseName,
DWORD dwDesiredAccess
);

Does the code below look like I imported it correctly? I am marshalling the
strings and the DWORD correctly - yes? Do I have to do anyhting special if I
want to marshal the strings as const? What's the PInvoke way to pass a NULL
string to this WIN32 API? I would like to pass nulls for the strings as the
API documentation says this function defaults to the correct settings for my
needs...

[DllImport("AdvApi32.dll", SetLastError = true)]
static extern IntPtr OpenSCManager([MarshalAs(UnmanagedType.LPTStr)] string
machineName, [MarshalAs(UnmanagedType.LPTStr)] string databaseName, uint
desiredAccess);

I'm calling the function like this:

managerHandle = OpenSCManager(null, SERVICES_ACTIVE_DATABASE, (uint)
ServiceAccess.SC_MANAGER_ENUMERATE_SERVICE);
uint error = GetLastError();

Depending on what I pass for my machine name {tried Environment.MachineName
with no luck} I get bizarre error return code back and the handle may or may
not be 0. If the handle is not 0 and I try to use it I always get an
"invalid handle" error...

Any help would be appreciated...

--Richard
 
M

Mattias Sjögren

Richard,

I'd declare the function like this

[DllImport("AdvApi32.dll", SetLastError = true, CharSet=CharSet.Auto)]
static extern IntPtr OpenSCManager(string machineName, string
databaseName, uint desiredAccess);

And to get the error code, you should use Marshal.GetLastWin32Error,
not GetLastError.



Mattias
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top