1

I'm trying to learn how to work with windows native code from Java. For this I use the JNA library. I'm just starting to learn how to work with this library and ran into this problem. The ADsGetObject function call fails. Perhaps I did not fully understand how to convert data types and do not use them correctly.

Here is my code:

import com.sun.jna.Native;
import com.sun.jna.WString;
import com.sun.jna.platform.win32.Guid.REFIID;
import com.sun.jna.ptr.PointerByReference;
import com.sun.jna.win32.StdCallLibrary;
import com.sun.jna.platform.win32.WinNT.HRESULT;

public class GetUserAttribute {
    public static void main(String[] args) {
        getUser("CN=Scaner,OU=Services,DC=my,DC=domain");
    }

    public interface Activeds extends StdCallLibrary {
        Activeds INSTANCE = (Activeds) Native.load("Activeds", Activeds.class);
        HRESULT ADsGetObject(WString lpszPathName, REFIID riid, PointerByReference ppObject);
    }

    public static void getUser(String dn) {
        WString userDN = new WString(dn);
        REFIID riid = new REFIID();
        PointerByReference ppObject = new PointerByReference();
        HRESULT hr = Activeds.INSTANCE.ADsGetObject(userDN,riid,ppObject);
        System.out.println(hr);
    }

When executed, hr is 0x80004005 (Unspecified error). I would be grateful for any hints on what I'm doing wrong and maybe for an example of a working code.

Here is the code on VBS that works correctly. Would like to "translate" it into Java code:

Dim strUserDN = "CN=Scaner,OU=Services,DC=my,DC=domain" 
set objUser = GetObject("LDAP://" & strUserDN)
Wscript.echo objUser.cn

1 Answers1

1

You are not assigning a guid value to riid, so you are effectively setting it to IID_NULL ({00000000-0000-0000-0000-000000000000}). You need to set it to IID_IADs ({FD8256D0-FD15-11CE-ABC4-02608C9E7553}) instead.

That will cause ADsGetObject() (if successful) to set ppObject to point at an IADs interface. Make sure that you call IUnknown.Release() on ppObject when you are done using that interface.

Also, the thread that is calling ADsGetObject() must call CoInitialize/Ex() beforehand. And call CoUninitialize() when it is done using the COM library. You can use com.sun.jna.platform.win32.Ole32 for that.

See the examples at How to use CoInitializeEx method in com.sun.jna.platform.win32.Ole32. Also see JNA calling CoInitialize when loading a dll

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • It's really best *not* to call `CoUninitialize`, especially in a runtime environment where object destruction happens at a non-deterministic point in time. – IInspectable Mar 25 '23 at 07:35